【问题标题】:How can I filter a dataframe with undetermined number of columns using R?如何使用 R 过滤列数不确定的数据框?
【发布时间】:2019-08-27 11:46:39
【问题描述】:

我希望能够过滤(最好使用 Dplyr)具有不确定列数的多个数据帧。这些数据框有几列,其中一些以相同的后缀命名。所以,我要做的是过滤那些使用相同后缀命名的所有列具有相同值的行。

所以我有以下数据框:

  Consequence CANONICAL x_LOH y_LOH x3
1            x       YES False False 12
2            x        NO False False 43
3            x       YES False False 64
4            x        NO  True False 34
5            y       YES  True False 93
6            y        NO  True False 16
7            y       YES  True  True 32
8            y        NO  True  True 74
9            z       YES False  True 84
10           z        NO False  True 89

我想过滤数据框并仅选择具有后缀 (_LOH) 的列为“True”的行(注意!!:在此数据框中有 2 列,但在其他数据框中可能有只有一、三或四列带有后缀,我需要代码对所有情况都有用)

期望的输出是:

7            y       YES  True  True 32
8            y        NO  True  True 74

代码:

library(dplyr)

# Dataframe:

DF <- data.frame(Consequence = c(rep("x",4),rep("y",4),rep("z",4)),
                       CANONICAL = rep(c("YES","NO"),6),
                       x_LOH = c(rep("False", 3), rep("True", 5), rep("False",2), "True","False"),
                       y_LOH = c(rep("False", 6), rep("True",4), rep("False",2)),
                       x3=c(12,43,64,34,93,16,32,74,84,89,45,67))

# This obviously does not work

cols = names(DF)[grepl("_LOH", names(DF))]
DF %>% filter
 (for(i in 1:length(cols)){
   cols[i] == "True"
})

任何想法将不胜感激。

谢谢

【问题讨论】:

    标签: r dataframe filter dplyr


    【解决方案1】:

    你可以试试:

    DF %>%
     filter_at(vars(ends_with("_LOH")), all_vars(. == "True"))
    
      Consequence CANONICAL x_LOH y_LOH x3
    1           y       YES  True  True 32
    2           y        NO  True  True 74
    

    base R类似:

    ind <- endsWith(names(DF), "_LOH")
    DF[rowSums(DF[, ind] == "True") == sum(ind), ]
    

    【讨论】:

      【解决方案2】:

      使用base R,我们可以选择以"LOH"结尾的列,并选择所有值为"True"的行

      cols <- grep("_LOH$", names(DF))
      DF[rowSums(DF[cols] == "True") == length(cols), ]
      
      #  Consequence CANONICAL x_LOH y_LOH x3
      #7           y       YES  True  True 32
      #8           y        NO  True  True 74
      

      或者使用apply

      DF[apply(DF[cols] == "True", 1, all), ]
      

      在这里,这也可以工作,但会发出警告,说明字符值被强制为逻辑值。

      DF[apply(DF[cols], 1, all), ]
      

      【讨论】:

        【解决方案3】:

        另一个基本 R 选项:

        isT <- function(x, y) x == "True" & y == "True"
        subset(DF, Reduce(isT, DF[endsWith(names(DF), "_LOH")]), )
        
        #   Consequence CANONICAL x_LOH y_LOH x3
        # 7           y       YES  True  True 32
        # 8           y        NO  True  True 74
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 2021-03-16
          • 1970-01-01
          相关资源
          最近更新 更多