【问题标题】:Is there a way to select rows from different columns with similar suffixes in a data.frame?有没有办法从 data.frame 中具有相似后缀的不同列中选择行?
【发布时间】:2019-03-04 03:19:14
【问题描述】:

我在R中有一个数据框如下

PROBE_ID    H_1AVG_Signal   H_1Detection Pval   H_2AVG_Signal   H_2Detection Pval   GH_1AVG_Signal  GH_1Detection Pval
ILMN_1343291    47631.78    0.00            53022.43    0.00            46567.29    0.00
ILMN_1651229    135.42      0.01            161.59      0.01            162.46      0.04
ILMN_1651260    80.81       0.86            88.05       0.86            92.45       0.89
ILMN_1651279    143.65      0.01            138.96      0.04            113.29      0.47

是否有任何可能的方法来对包含检测 p 值

PROBE_ID    H_1AVG_Signal   H_1Detection Pval   H_2AVG_Signal   H_2Detection Pval   GH_1AVG_Signal  GH_1Detection Pval
ILMN_1343291    47631.78    0.00            53022.43    0.00            46567.29    0.00
ILMN_1651229    135.42      0.01            161.59      0.01            162.46      0.04

我非常感谢有关如何创建这样一个子集的建议。 谢谢。

【问题讨论】:

  • 欢迎来到 StackOverflow!请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。
  • 可能你需要类似:df[rowSums(df[, grepl('Detection Pval', names(df), fixed = TRUE)] < 0.05) > 0, ]
  • @Jaap,谢谢。我编辑了我的问题,希望现在更好。我尝试了代码并得到了矩阵错误(unlist(value,recursive = FALSE,use.names = FALSE),nrow = nr,:'data'必须是向量类型,是'NULL'
  • class(name_of_your_dataframe) 返回什么?
  • @Jaap 它返回“data.frame”

标签: r


【解决方案1】:

如果你总是知道你将拥有的列名,那么你可以使用 dplyr 过滤器来获得你想要的结果

library(dplyr)

main.df <- main.df %>%
           filter(`H_1Detection Pval` < 0.05 | `H_2Detection Pval` < 0.05 | `GH_1Detection Pval` < 0.05)

如果您不总是知道列名,您可以动态获取它们并将它们插入到 dplyr filter_ 命令中,如下所示

library(dplyr)
# Find any columns that contain "detection" in the column name
det.cols <- colnames(main.df)[which(grepl("detection",tolower(colnames(main.df))))]

# Create a filter string from the column names in the format of
# "`column name` < 0.05 | `column name2` < 0.05"
filt <- gsub(","," | ",toString(paste("`",det.cols,"`"," < 0.05", sep = "")))

# Apply the filter to the dataframe
main.df <- main.df %>%
           filter_(filt)

【讨论】:

  • 谢谢。对于将过滤器应用于数据帧的最后一个代码,我收到“解析错误(文本 = x):尝试使用零长度变量名”
  • 确保替换det.cols &lt;- colnames( main.df )[which(grepl("detection",tolower(colnames( main.df 中的两个main.df 实例b> ))))] 与您正在使用的数据框的名称。
  • 我确实用我的数据名称替换了 main.df。我只收到最后一个代码的错误。
  • 我猜它没有得到列名中包含“检测”的列的任何匹配项,这会为 det.cols 创建一个空向量。因为 det.cols 是空的,所以导致错误发生在最后一行。请注意,此代码将列名作为所有小写字母进行比较,因此请确保将 det.cols 行中的 grepl 模式保持为所有小写字母,否则将不会返回任何值。
  • 我尝试将标题更改为小写,它返回过滤后的数据而没有错误消息。但是现在过滤后的数据有 ILMN_1651279 基因,对于第三个样本,该基因的检测 pval > 0.05。
【解决方案2】:

filter_at 是一种更简单的动态检测列的方法,如R dplyr filtering data with values greater than +N and lesser than -N : abs() function? 中所述

main.df %&gt;% filter_at(vars(contains("Detection Pval")), .vars_predicate = any_vars(. &lt; 0.5))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2020-12-20
    • 2019-05-06
    • 2022-11-15
    相关资源
    最近更新 更多