Liondancer
Liondancer

Reputation: 16469

Find number of rows where both values are 0

I am trying to figure out the number of rows that have col1 != 0 || col2 != 0

sample:

> head(df2$col1)
[1] 3 0 2 1 0 5
> head(df2$col2)
[1] 0 0 0 0 0 0

What I tried:

>dim(df2)
[1] 38272    69
> jj = df2[df2$col1 != 0 || df2$col2 != 0]
> dim(jj)
[1] 38272    69

Not sure why the dimensions are the same even though you can clearly see from the head() that there is an example where col1 and col2 is 0

Upvotes: 0

Views: 72

Answers (2)

Mahdi Baghbanzadeh
Mahdi Baghbanzadeh

Reputation: 548

I strongly recommend you to study the dplyr package documentation:

library(dplyr)

new_dff <- df2 %>%
         filter(col1==0, col2==0)

Upvotes: 0

www
www

Reputation: 39154

df2$col1 != 0 || df2$col2 != 0 matches everything because it reads as col1 is not 0 OR col2 is not 0. If you want to find col1 is 0 AND col2 is 0, please use the following.

df2 <- data.frame(col1 = c(3, 0, 2, 1, 0, 5),
                  col2 = c(0, 0, 0, 0, 0, 0))

df2[df2$col1 == 0 & df2$col2 == 0, ]
  col1 col2
2    0    0
5    0    0

nrow(df2[df2$col1 == 0 & df2$col2 == 0, ])
# [1] 2

Upvotes: 1

Related Questions