How to remove rows where all columns are zero using dplyr pipe

前端 未结 5 720
醉梦人生
醉梦人生 2021-01-18 07:41

I have the following data frame:

dat <- structure(list(`A-XXX` = c(1.51653275922944, 0.077037240321129, 
0), `fBM-         


        
5条回答
  •  误落风尘
    2021-01-18 08:25

    Adding to the answer by @mgrund, a shorter alternative with dplyr 1.0.0 is:

    # Option A:
    data %>% filter(across(everything(.)) != 0))
    
    # Option B:
    data %>% filter(across(everything(.), ~. == 0))
    

    Explanation:
    across() checks for every tidy_select variable, which is everything() representing every column. In Option A, every column is checked if not zero, which adds up to a complete row of zeros in every column. In Option B, on every column, the formula (~) is applied which checks if the current column is zero.

    EDIT:
    As filter already checks by row, you don't need rowwise(). This is different for select or mutate.

    IMPORTANT:
    In Option A, it is crucial to write across(everything(.)) != 0,
    and NOT across(everything(.) != 0))!

    Reason:
    across requires a tidyselect variable (here everything()), not a boolean (which would be everything(.) != 0))

提交回复
热议问题