如何在 R 中创建一个双向表?
在本文中,我们将使用 R 编程语言创建一个双向表。
双向表用于显示两个分类变量的频率。行代表分类特征,列代表频率。我们可以使用 as.table() 方法创建双向表。 R 语言中的 as.table()函数用于将对象转换为表格。
Syntax:
as.table(x)
Parameters:
x: Object to be converted
从矩阵创建一个双向表
在这里,我们将从矩阵创建一个表。
示例:来自 Matrix 的表格
R
# create matrix with 3 columns
data = matrix(c(1:6), ncol=3)
# specify row and column names
rownames(data) = c('Fruits', 'vegetables')
colnames(data) = c('apple', 'banana', 'lemon')
# convert matrix to table
data = as.table(data)
# display
data
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display
data
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display barplot
barplot(data, main='Eatables')
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display mosaicplot
mosaicplot(data, main='Eatables')
输出:
从数据框创建一个双向表
我们将使用 table() 方法从数据框创建双向表。
语法;
table(df$column1, df$column2,...,df$column n)
其中,df 是输入数据帧
示例:来自 Dataframe 的表
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display
data
输出:
可视化两路表
我们可以使用 barplot()函数查看双向表的条形图
语法:
barplot(data)
其中,数据是输入数据帧
示例:条形图可视化
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display barplot
barplot(data, main='Eatables')
输出:
我们还可以显示马赛克图。
语法:
mosaicplot(data)
示例:马赛克图可视化
R
# create dataframe with 2 columns
data = data.frame(col1=c("apple","mango","mango","guava","apple"),
col2=c("fruit","veg","fruit","fruit","veg"))
# convert dataframe to table
data = table(data$col1,data$col2)
# display mosaicplot
mosaicplot(data, main='Eatables')
输出: