Remove columns of dataframe based on conditions in R

前端 未结 2 509
死守一世寂寞
死守一世寂寞 2020-12-10 00:00

I have to remove columns in my dataframe which has over 4000 columns and 180 rows.The conditions I want to set in to remove the column in the dataframe are: (i) Remove the c

2条回答
  •  一生所求
    2020-12-10 00:24

    Create logical vectors for each condition:

    # condition 1
    cond1 <- sapply(df, function(col) sum(!is.na(col)) < 2)
    
    # condition 2
    cond2 <- sapply(df, function(col) !any(diff(which(!is.na(col))) == 1))
    
    # condition 3
    cond3 <- sapply(df, function(col) all(is.na(col)))
    

    Then combine them into one mask:

    mask <- !(cond1 | cond2 | cond3)
    
    > df[,mask,drop=F]
           A     E
    1  0.018    NA
    2  0.017    NA
    3  0.019    NA
    4  0.018    NA
    5  0.018    NA
    6  0.015 0.037
    7  0.016 0.031
    8  0.019 0.025
    9  0.016 0.035
    10 0.018 0.035
    11 0.017 0.043
    12 0.023 0.040
    13 0.022 0.042
    

提交回复
热议问题