Home > Software engineering >  How to filter across any columns for na and empty value but not 0
How to filter across any columns for na and empty value but not 0

Time:08-31

Here's my dataframe:

df1 = structure(list(item = c("HY04SB", "GSP8Y1", "8OK8N6", "V2RIP7", 
"51H9V8", "", "5C45YN", "PM271I", "4WVDD9"), weird = c("", "", 
"", "v1b m#|1", "f%nfw j<", "[3-qzg76", "13k{-ftr", "", "sywf|*l!"
), simple = c(14661746L, NA, 88171210L, NA, 0L, 35586016L, NA, 
0L, 23761616L), code = c("WX&}Awx:65Dgn9A3", "0", "7jcP!&EAJFT=4=Xv", 
"}7p92w~STX>2M5TP", "", "EvEH hV=}6X,aS'Q", "", "r*C'U9LA\"tr$p_X;", 
"0")), class = "data.frame", row.names = c(NA, -9L))

> df1 
    item    weird   simple             code
1 HY04SB          14661746 WX&}Awx:65Dgn9A3
2 GSP8Y1                NA                0
3 8OK8N6          88171210 7jcP!&EAJFT=4=Xv
4 V2RIP7 v1b m#|1       NA }7p92w~STX>2M5TP
5 51H9V8 f%nfw j<        0                 
6        [3-qzg76 35586016 EvEH hV=}6X,aS'Q
7 5C45YN 13k{-ftr       NA                 
8 PM271I                 0 r*C'U9LA"tr$p_X;
9 4WVDD9 sywf|*l! 23761616                0

I'm not sure how to make the below syntax to work in order to retrieve any rows that contain empty value and na but not 0

df1_na_empty_but_not_zero <- df1 %>% 
          filter(if_any(item: code %in% c(~ is.na(.), ~ !.x == "0", ~.x == "")))

Expected output:

item    weird   simple             code
1 HY04SB          14661746 WX&}Awx:65Dgn9A3
3 8OK8N6          88171210 7jcP!&EAJFT=4=Xv
4 V2RIP7 v1b m#|1       NA }7p92w~STX>2M5TP
6        [3-qzg76 35586016 EvEH hV=}6X,aS'Q
7 5C45YN 13k{-ftr       NA       

      

Can someone help please? Thanks.

CodePudding user response:

You need to set 2 conditions:

library(dplyr)

df1 %>%
  filter(if_any(item:code, ~ .x == "" | is.na(.x)),
         if_all(item:code, ~ .x != 0  | is.na(.x)))

#     item    weird   simple             code
# 1 HY04SB          14661746 WX&}Awx:65Dgn9A3
# 2 8OK8N6          88171210 7jcP!&EAJFT=4=Xv
# 3 V2RIP7 v1b m#|1       NA }7p92w~STX>2M5TP
# 4        [3-qzg76 35586016 EvEH hV=}6X,aS'Q
# 5 5C45YN 13k{-ftr       NA
  • Related