Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

r - Count number of zeros per row, and remove rows with more than n zeros

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

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

Is that possible?? Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's not only possible, but very easy:

DF[rowSums(DF == 0) <= 4, ]

You could also use apply:

DF[apply(DF == 0, 1, sum) <= 4, ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...