【问题标题】:how to use a variable in grepl function within a loop-R如何在循环-R中的grepl函数中使用变量
【发布时间】:2013-05-21 13:19:49
【问题描述】:

我是 R 新手,在循环和 grepl 函数方面存在一些问题 我有一个类似的数据:

str(peptidesFilter)
  'data.frame':   78389 obs. of  130 variables:
 $ Sequence                      : chr  "AAAAAIGGR" "AAAAAIGGRPNYYGNEGGR" "AAAAASSNPGGGPEMVR" "AAAAAVGGR" ...
 $ First.amino.acid              : chr  "A" "A" "A" "A" ...
 $ Protein.group.IDs             : chr  "1" "1;2;4" "2;5 "3" "4;80" ...

我想使用下面的grepl函数根据$ Protein.group.IDs过滤数据

    peptidesFilter.new <- peptidesFilter[grepl('(^|;)2($|;)',
peptidesFilter$Protein.group.IDs),]

我想对每个单独的数据(例如 1、2、3 等...)进行循环 并重写包含变量peptidesFilter.i的数据框的名称

   i =1
   while( i <= N) { peptidesFilter.[[i]] <- 
   peptidesFilter[grepl('(^|;)i($|;)',
   peptidesFilter$Protein.group.IDs),] 
    i=i+1 }

我有两个问题, grep1 函数中的主要 i 不被识别为变量以及如何以包含变量的方式重命名过滤数据。

有什么想法吗?

【问题讨论】:

    标签: r loops variables


    【解决方案1】:

    对于 grepl 问题,您可以使用 paste0 例如:

    paste0('(^|;)',i,'($|;)')
    

    对于循环,你可以这样:

    ll <- lapply(seq(1:4),function(x)
             peptidesFilter[grepl(paste0('(^|;)',x,'($|;)'),
                               peptidesFilter$Protein.group.IDs),])
    

    然后您可以将其转换为 data.frame:

    do.call(rbind,ll)
    
                Sequence First.amino.acid Protein.group.IDs
    1            AAAAAIGGR                A                 1
    2  AAAAAIGGRPNYYGNEGGR                A             1;2;4
    21 AAAAAIGGRPNYYGNEGGR                A             1;2;4
    3    AAAAASSNPGGGPEMVR                A               2;5
    4            AAAAAVGGR                A                 3
    22 AAAAAIGGRPNYYGNEGGR                A             1;2;4
    

    【讨论】:

    • 非常感谢! paste0('(^|;)',i,'($|;)') 解决了 grep1 的问题,我无法理解 lapply,基本上我想根据 ID 拆分数据,然后进一步处理每个拆分的数据。例如序列信息。 do.call(rbind,ll),它再次组合了所有数据。是否可以在 x=1、x=2 等时创建单独的数据框(例如肽过滤器x1、肽过滤器x2 等)……还是我理解错了?
    • @Samir 清单 ll 就是我想的你想要的。
    • 对不起,我现在想通了。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多