filter rows when all columns greater than a value

前端 未结 1 1149
南旧
南旧 2021-01-03 08:38

I have a data frame and I would like to subset the rows where all columns values meet my cutoff.

here is the data frame:

   A B C
1  1 3 5
2  4 3 5
         


        
1条回答
  •  鱼传尺愫
    2021-01-03 08:49

    We can create a logical matrix my comparing the entire data frame with 2 and then do rowSums over it and select only those rows whose value is equal to number of columns in df

    df[rowSums(df > 2) == ncol(df), ]
    
    #  A B C
    #2 4 3 5
    

    A dplyr approach using filter_all and all_vars

    library(dplyr) 
    df %>%
     filter_all(all_vars(. > 2))
    
    #  A B C
    #1 4 3 5
    

    An apply approach

    df[apply(df > 2, 1, all), ]
    

    0 讨论(0)
提交回复
热议问题