【问题标题】:If string contains any element of vector如果字符串包含向量的任何元素
【发布时间】:2014-05-25 11:15:25
【问题描述】:

我有这样一个问题: 我有 2 个 txt 文件。 一个看起来像这样:

ABCG1
ABLIM1
ABP1
ACOT11
ACP5

并且包含 700+ 个字符串,第二个看起来像这样:

1       2       3       4       5       6       GENE_NAME
0.01857 0.02975 0.02206 0.01847 0.01684 0.01588 NIPA2;NIPA2;NIPA2;NIPA2
0.81992 0.8168  0.76963 0.83116 0.78114 0.85544 MAN1B1
0.13053 0.12308 0.10654 0.11675 0.13664 0.10312 TSEN34;TSEN34
0.91888 0.93095 0.91498 0.91558 0.91126 0.91569 LRRC16A

它的尺寸是90+x640 000+

我想提取第二个制表符分隔文件的字符串,其中包含第一个的任何值。我想到了类似的东西:

data=x[1,]
data=data[-1,]
for (i in 1:nrow(test)){
    if (grepl("gene_name",test[i,]$GENE_NAME=="TRUE")){
    data_temp=x[i,]
    data=rbind(data,data_temp)
    rm(data_temp)
    }

但问题是我必须重复此代码 700 多次。有没有办法这样写:

value= c(vector that contains my gene names)
string= (one of srings of my table)
grepl(any(value),string)

我遇到了any 的问题,因为它使向量逻辑而不是字符。 先感谢您。

【问题讨论】:

  • 如果您在第一个文件中添加“GENE_NAME”作为列标题,您可以这样做:merge(df1,df2,by="GENE_NAME")。其中 df1 和 df2 是作为数据框的文件

标签: regex string r extract


【解决方案1】:

这对你有用吗?

value <- c("ABCG1",
          "ABLIM1",
          "ABP1",
          "ACOT11",
          "ACP5")


GENE_NAME <- c("ABCG1;NIPA2;NIPA2",
           "ABLIM1",
           "ABP1;ABCG1",
           "ACOT11",
           "TSEN34;TSEN34",
           "ACP5",
           "LRRC16A") # This is the test$GENE_NAME column

lapply(value, function(x) GENE_NAME[grepl(x, GENE_NAME)])
# [[1]]
# [1] "ABCG1;NIPA2;NIPA2" "ABP1;ABCG1"       
# 
# [[2]]
# [1] "ABLIM1"
# 
# [[3]]
# [1] "ABP1;ABCG1"
# 
# [[4]]
# [1] "ACOT11"
# 
# [[5]]
# [1] "ACP5"

如果你喜欢,你可以取消列出它

unlist(lapply(value, function(x) GENE_NAME[grepl(x, GENE_NAME)]))
# [1] "ABCG1;NIPA2;NIPA2" "ABP1;ABCG1"        "ABLIM1"            "ABP1;ABCG1"        "ACOT11"           
# [6] "ACP5" 

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2020-01-07
    • 2019-03-13
    • 2023-03-04
    相关资源
    最近更新 更多