本文介绍了计算每行零个数,并删除多于n个零的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于每行计数零的问题。我有一个这样的数据框:
I have a question about counting zeros per row. I have a dataframe like this:
a = c(1,2,3,4,5,6,0,2,5)
b = c(0,0,0,2,6,7,0,0,0)
c = c(0,5,2,7,3,1,0,3,0)
d = c(1,2,6,3,8,4,0,4,0)
e = c(0,4,6,3,8,4,0,6,0)
f = c(0,2,5,5,8,4,2,7,4)
g = c(0,8,5,4,7,4,0,0,0)
h = c(1,3,6,7,4,2,0,4,2)
i = c(1,5,3,6,3,7,0,5,3)
j = c(1,5,2,6,4,6,8,4,2)
DF<- data.frame(a=a,b=b,c=c,d=d,e=e,f=f,g=g,h=h,i=i,j=j)
a b c d e f g h i j
1 1 0 0 1 0 0 0 1 1 1
2 2 0 5 2 4 2 8 3 5 5
3 3 0 2 6 6 5 5 6 3 2
4 4 2 7 3 3 5 4 7 6 6
5 5 6 3 8 8 8 7 4 3 4
6 6 7 1 4 4 4 4 2 7 6
7 0 0 0 0 0 2 0 0 0 8
8 2 0 3 4 6 7 0 4 5 4
9 5 0 0 0 0 4 0 2 3 2
我想计算每行零个数字。如果每行的零个数目大于某个特定数目,例如4,我想删除整个行。结果数据框如下所示:
I want to count the numbers of zeros per row. If the number of zeros per row is more than a certain number, say 4, I want to remove the complete row. The resulting dataframe looks like this:
a b c d e f g h i j
2 2 0 5 2 4 2 8 3 5 5
3 3 0 2 6 6 5 5 6 3 2
4 4 2 7 3 3 5 4 7 6 6
5 5 6 3 8 8 8 7 4 3 4
6 6 7 1 4 4 4 4 2 7 6
8 2 0 3 4 6 7 0 4 5 4
有可能吗?谢谢!
推荐答案
这不仅可能,而且非常简单:
It's not only possible, but very easy:
DF[rowSums(DF == 0) <= 4, ]
您也可以使用 apply
:
DF[apply(DF == 0, 1, sum) <= 4, ]
这篇关于计算每行零个数,并删除多于n个零的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!