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

前端 未结 5 666
醉梦人生
醉梦人生 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:26

    Here's a dplyr option:

    library(dplyr)
    filter_all(dat, any_vars(. != 0))
    
    #       A-XXX  fBM-XXX    P-XXX  vBM-XXX
    #1 1.51653276 2.228752 1.733567 3.003979
    #2 0.07703724 0.000000 0.000000 0.000000
    

    Here we make use of the logic that if any variable is not equal to zero, we will keep it. It's the same as removing rows where all variables are equal to zero.

    Regarding row.names:

    library(tidyverse)
    dat %>% rownames_to_column() %>% filter_at(vars(-rowname), any_vars(. != 0))
    #         rowname      A-XXX  fBM-XXX    P-XXX  vBM-XXX
    #1  BATF::JUN_AHR 1.51653276 2.228752 1.733567 3.003979
    #2 BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000
    

提交回复
热议问题