我有一个关于每行计数零的问题。我有这样的数据框:
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,我想删除整行。结果数据框如下所示:
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
可能吗?谢谢!
答案 0 :(得分:34)
这不仅可行,而且非常简单:
DF[rowSums(DF == 0) <= 4, ]
您也可以使用apply
:
DF[apply(DF == 0, 1, sum) <= 4, ]