【问题标题】:R subset data.frame by column names using partial string match from another listR 使用来自另一个列表的部分字符串匹配的列名子集 data.frame
【发布时间】:2021-12-07 14:32:48
【问题描述】:

我有一个这样的数据框(称为“myfile”):

      P3170.Tp2  P3189.Tn10 C453.Tn7 F678.Tc23 P3170.Tn10
gene1 0.3035130  0.5909081 0.8918271 0.2623648 0.13392672
gene2 0.2542919  0.5797730 0.4226669 0.9091961 0.96056308
gene3 0.9923911  0.4318736 0.7020107 0.1936181 0.58723105
gene4 0.4113318  0.1239206 0.4091794 0.8196982 0.54791214
gene5 0.4095719  0.6392045 0.4416208 0.8853356 0.01008299

我有一个有趣的字符串列表(称为“interesting.list”),如下所示:

interesting.list <- c("P3170", "C453")

我想使用这个有趣的.list 并通过列标题的部分字符串匹配来子集 myfile。

ss.file <- NULL
for (i in 1:length(interesting.list)){
    ss.file[[i]] <- myfile[,colnames(myfile) %like% interesting.list[[i]]]
}

但是,此循环在运行后不提供列标题。 由于我有一个庞大的数据集(超过 30000 行),因此很难手动实现 colnames。有更好的方法吗?

【问题讨论】:

  • 查看grep()。您可以用“|”分隔interesting.list 中的每个项目对于单行,不需要循环,例如,df[,grep("P3170|C453", x=names(df))]
  • 是的,问题是我的有趣列表中有一个巨大的列表(大约 3000 个)。
  • 好的!这不应该是我回答中的第二种方法的问题。

标签: r subset


【解决方案1】:
# Specify `interesting.list` items manually
df[,grep("P3170|C453", x=names(df))]
#>   P3170.Tp2 C453.Tn7 P3170.Tn10
#> 1         1        3          5

# Use paste to create pattern from lots of items in `interesting.list`
il <- c("P3170", "C453")
df[,grep(paste(il, collapse = "|"), x=names(df))]
#>   P3170.Tp2 C453.Tn7 P3170.Tn10
#> 1         1        3          5

示例数据:

n <- c("P3170.Tp2" , "P3189.Tn10" ,"C453.Tn7" ,"F678.Tc23" ,"P3170.Tn10")
df <- data.frame(1,2,3,4,5)
names(df) <- n
Created on 2021-10-20 by the reprex package (v2.0.1)

【讨论】:

  • 太棒了。第二个解决方案,奏效了。谢谢!
  • 不客气。祝你好运
  • 嗨@biobudhan,如果你认为这是最好的答案,你介意接受它是正确的,以便未来的读者更容易找到它吗?
  • 现在接受答案!谢谢!!
【解决方案2】:

除了这个问题,您还需要考虑很多事情;如果interesting.list 中的一个项目返回多个匹配项,如果没有找到匹配项怎么办,等等。

根据您的数据,这是一种方法:

nms <- colnames(myFile)

matchIdx <- unlist(lapply(interesting.list, function(pattern) {
  matches <- which(grepl(pattern, nms, fixed = TRUE))

  # If more than one match is found, only return the first
  if (length(matches) > 1) matches[1] else matches
}))

myFile[, matchIdx, drop = FALSE]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2016-10-18
    • 2015-11-03
    • 2017-03-14
    • 2020-03-29
    • 2022-01-07
    • 2021-04-19
    相关资源
    最近更新 更多