简体   繁体   English

R- 计数 data.frame 中的值

[英]R- count values in data.frame

df <- data.frame(row.names = c('ID1','ID2','ID3','ID4'),var1 = c(0,1,2,3),var2 = c(0,0,0,0),var3 = c(1,2,3,0),var4 = c('1','1','2','2'))
> df
    var1 var2 var3 var4
ID1    0    0    1    1
ID2    1    0    2    1
ID3    2    0    3    2
ID4    3    0    0    2

I want df to look like this我希望 df 看起来像这样

   var1  var2  var3  var4
0   1     4     1     0
1   1     0     1     2
2   1     0     1     2
3   1     0     1     0

So I want the values of df to be counted.所以我希望计算 df 的值。 The problem is, that not every value occurs in every column.问题是,并非每个值都出现在每一列中。 I tried this lapply(df,table) but that returns a list which I cannot convert into a data.frame (because of said reason).我尝试了这个lapply(df,table)但它返回了一个我无法转换为 data.frame 的列表(由于上述原因)。 I could do it kind of manually with table(df$var1) and bind everything together after doing that with every var, but that is boring.我可以使用table(df$var1)手动执行此操作,并在对每个 var 执行此操作后将所有内容绑定在一起,但这很无聊。 Can you find a better way?你能找到更好的方法吗?

Thanks;)谢谢;)

Call table function with factor levels which are present in the entire dataset.调用table function 以及整个数据集中存在的因子水平。

sapply(df,function(x) table(factor(x, levels = 0:3)))

#  var1 var2 var3 var4
#0    1    4    1    0
#1    1    0    1    2
#2    1    0    1    2
#3    1    0    1    0

If you don't know beforehand what levels your data can take, we can find it from data itself.如果您事先不知道您的数据可以达到什么级别,我们可以从数据本身中找到它。

vec <- unique(unlist(df))
sapply(df, function(x) table(factor(x, levels = vec)))

We could do this without any loop我们可以在没有任何循环的情况下做到这一点

table(c(col(df)), unlist(df))

#    0 1 2 3
#   1 1 1 1 1
#   2 4 0 0 0
#   3 1 1 1 1
#   4 0 2 2 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM