counting the number of values greater than 0 in R in multiple columns

て烟熏妆下的殇ゞ 提交于 2020-01-30 13:03:33

问题


I have a dataset myDF in R with a the variables L1,L2,L3,L4. How can I get the number of observations in L2, L3, and L4 that area greater than 0?

I would like to use the subset function, I'm just not sure how Thanks!

L1     L2     L3    L4
1       1     0     2
2       1     4     1 
3       1     3     1
2       2     1     1

I would like to be able to create a function that would be able to tally up the number of rows in columns L2, L3, and L4 greater than 0.


回答1:


We can use

colSums(myDF[c("L2", "L3", "L4")] > 0)



回答2:


I don't think colSums will give you the right answer since it doesn't counts the number of observations, but only sums the columns' values.

I think that this will give you what you want , I hope.

apply(myDF,2,function(x) sum(x > 0))


来源:https://stackoverflow.com/questions/41729336/counting-the-number-of-values-greater-than-0-in-r-in-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!