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

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

    We could use reduce from purrr to get the sum of rows and filter the dataset based on the logical vector

    library(tidyverse)
    dat %>%
        reduce(`+`) %>%
        {. != 0} %>% 
       filter(dat, .)
    #       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
    

    NOTE: Within the %>%, the row.names gets stripped off. It may be better to create a new column or assign row.names later


    If we need the row names as well, then create a row names column early and then use that to change the row names at the end

    dat %>%
      rownames_to_column('rn') %>%
      filter(rowSums(.[-1]) != 0) %>% 
      `row.names<-`(., .[['rn']]) %>% select(-rn)
    #                   A-XXX  fBM-XXX    P-XXX  vBM-XXX
    #BATF::JUN_AHR  1.51653276 2.228752 1.733567 3.003979
    #BATF::JUN_CCR9 0.07703724 0.000000 0.000000 0.000000
    

提交回复
热议问题