R 数据帧的列计数表
我有一个数据框架,其中包含以字符串形式提供的分类数据列。每列的类别相同,例如:R 数据帧的列计数表,r,dataframe,apply,tabular,R,Dataframe,Apply,Tabular,我有一个数据框架,其中包含以字符串形式提供的分类数据列。每列的类别相同,例如: myDF=data.frame(col1=sample(c("a","b","c"),10,replace=T), col2=sample(c("a","b","c"),10,replace=T), col3=sample(c("a","b","c"),10,replace=T)) 我想按列生成每个类别的计数表 当所有列都包含所有类别时,可以使用函数t
myDF=data.frame(col1=sample(c("a","b","c"),10,replace=T),
col2=sample(c("a","b","c"),10,replace=T),
col3=sample(c("a","b","c"),10,replace=T))
我想按列生成每个类别的计数表
当所有列都包含所有类别时,可以使用函数table
通过apply
实现,例如:
> myDF
col1 col2 col3
1 a c a
2 b b b
3 a a b
4 b b a
5 c c a
6 a a a
7 a c c
8 a a c
9 c a a
10 a a b
> apply(myDF,2,table)
col1 col2 col3
a 6 5 5
b 2 2 3
c 2 3 2
但是,如果一列缺少某些类别,这将不起作用,因为table
不知道需要哪些类别:
myDF=data.frame(col1=sample(c("a","b","c"),10,replace=T),
col2=sample(c("a","b","c"),10,replace=T),
col3=sample(c("a","b"),10,replace=T))
给出:
> myDF
col1 col2 col3
1 c a a
2 a a b
3 b a a
4 c c a
5 c a a
6 c c a
7 c b a
8 c b b
9 a a a
10 b b a
> apply(myDF,2,table)
$col1
a b c
2 2 6
$col2
a b c
5 3 2
$col3
a b
8 2
如何生成一个与第一个表相似的表,其中0表示任何缺少的类别?您可以收集所有因子级别,并在
应用中使用它们:
#get the levels from the whole data.frame
all_levels <- levels(unlist(myDF))
#convert each column to factor using the levels from above
#and then use table (which will return a zero for any missing levels)
apply(myDF, 2, function(x) table(factor(x, levels = all_levels)))
我们可以使用mtabulate
library(qdapTools)
t(mtabulate(myDF))
# col1 col2 col3
#a 2 5 8
#b 2 3 2
#c 6 2 0
它适用于OP文章中提到的两种情况在示例中效果非常好。对于真实的数据,列还没有强制转换为因子,但我成功地使用了相同的方法,用unique
代替levels
。听起来很棒!很乐意提供帮助:)另请参见类似于table(stack(lappy(myDF,as.character)))的内容。
library(qdapTools)
t(mtabulate(myDF))
# col1 col2 col3
#a 2 5 8
#b 2 3 2
#c 6 2 0