Extracting columns having greater than certain values in R dataframe

前端 未结 5 1643
滥情空心
滥情空心 2021-01-26 22:14

I have a dataframe:

Alix    Blim    Jux Gyno
0.105   0.234   0.67    0.89
0.01    0.542   0.11    0.65
0.003   0.002   0.6     0.67
0.009   0.123   0.09    0.01
         


        
相关标签:
5条回答
  • 2021-01-26 22:43

    We could use colSums to subset columns using base R

    df[colSums(df > 0.6) > 0]
    
    # Jux Gyno
    #1 0.67 0.89
    #2 0.11 0.65
    #3 0.60 0.67
    #4 0.09 0.01
    

    Or with dplyr, select_if

    library(dplyr)
    df %>% select_if(~any(. > 0.6))
    
    0 讨论(0)
  • 2021-01-26 22:50

    here is a base R option with Filter

    Filter(function(x) any(x > 0.6), df)
    #  Jux Gyno
    #1 0.67 0.89
    #2 0.11 0.65
    #3 0.60 0.67
    #4 0.09 0.01
    

    Or using transmute_if

    library(dplyr)
    df %>% 
        transmute_if(~ any(.x > 0.6), I)
    

    Or with keep

    library(purrr)
    keep(df, map_lgl(df, ~ any(.x > 0.6)))
    
    0 讨论(0)
  • 2021-01-26 22:52
    df <- read.table(text='Alix    Blim    Jux Gyno
    0.105   0.234   0.67    0.89
    0.01    0.542   0.11    0.65
    0.003   0.002   0.6     0.67
    0.009   0.123   0.09    0.01
    ', header=T)
    

    We can use sapply to find the max value in each column, then check if it's greater than 0.6. This gives a logical vector which we can use to subset df by column:

    df[,sapply(df, max) > 0.6]
    
       Jux Gyno
    1 0.67 0.89
    2 0.11 0.65
    3 0.60 0.67
    4 0.09 0.01
    
    0 讨论(0)
  • 2021-01-26 23:02

    Please provide a reproducible example for future questions.

    Here is my dplyr solution:

    library(tidyverse)
    
    df <- tibble(First = 0:5,
                 Second = 10:15,
                 Third = 20:25)
    
    is_greater_than <- function(x) any(x > 10)
    
    select_if(df, is_greater_than)
    
    0 讨论(0)
  • 2021-01-26 23:05
    > df[ , sapply(df, function(x) any(x>0.6))]
       Jux Gyno
    1 0.67 0.89
    2 0.11 0.65
    3 0.60 0.67
    4 0.09 0.01
    
    0 讨论(0)
提交回复
热议问题