简体   繁体   English

如何在循环-R中的grepl函数中使用变量

[英]how to use a variable in grepl function within a loop-R

I am new to R and, have some problems with looping and grepl functions I have a data from like:我是 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" ...

I want to filter the data according to $ Protein.group.IDs by using grepl function below我想使用下面的 grepl 函数根据 $ Protein.group.IDs 过滤数据

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

I want to do it with a loop for every individual data ( eg 1, 2, 3, etc...) and re-write name of data frame containing variable peptidesFilter.i我想对每个单独的数据(例如 1、2、3 等...)进行循环并重写包含变量肽段过滤器.i 的数据框的名称

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

i have two problems, main one i in the grep1 function does not recognized as a variable and how i can re-name filtered data in a way it will contain variable.我有两个问题,主要的问题是我在 grep1 函数中无法识别为变量,以及如何以包含变量的方式重命名过滤数据。

any ideas?有任何想法吗?

For grepl problem you can use paste0 for example:对于 grepl 问题,您可以使用paste0例如:

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

For the loop , you can so something like this :对于循环,你可以这样:

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

then you can transform it to a data.frame:然后您可以将其转换为 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM