Home > Mobile >  detect 0 values across rows
detect 0 values across rows

Time:10-07

I would like to know how many rows that contain only 0 values using tidyverse

My example.

df <- data.frame(ID = c("a","b","c","d"),
                 x= c(0,0,1,1),
                 y = c(0,0,1,1))

All know is use base R as below

df[apply(df [,-1], 1, function(x) all(x==0)),]

Desired output what I want to see

ID x y
1  a 0 0
2  b 0 0

Any suggestions for me using tidyverse?

CodePudding user response:

We can use filter with if_any to return rows with any 0 values in numeric columns

library(dplyr)
df %>% 
   filter(if_any(where(is.numeric), ~ . == 0))
ID x y
1  a 0 0
2  b 0 0

Or may use across with rowSums

df %>% 
   filter(rowSums(across(where(is.numeric)) == 0) > 0)
  ID x y
1  a 0 0
2  b 0 0
  • Related