【问题标题】:Nested apply statement over a list of lists在列表列表上嵌套应用语句
【发布时间】:2019-06-27 19:17:58
【问题描述】:

我想提取 seq.df(单列 df)中与匹配 map.list(列表列表)中的索引匹配的蛋白质。

示例数据:

seq.df<- rbind.data.frame("MTHISPAVYGLWAIMSVLLAAFCAY",
    "MERSSAIVFPNVGTSVLSATIHLVGVTVLAHLISRRTALRGTST",
    "MLFEPFWCLLDLLRWSLDTHYIPAKRPLNGGGRSSNFD")
map.list<- list(a<- list(2,3,4,5,6,7),
    b<- list(13,14,30,31,32),
    c<- list(5,6,10,11))

期望的输出:

THISPA
GTAHL
PFLD

如果我只对 map.list 的第一个子列表运行嵌套应用,我会得到我想要的第一个蛋白质:

prot.list<- apply(seq.df, 1, function (x) lapply(map.list[[1]], function (y) substring(x, y, y)))

返回第一个序列的预期结果 (THISPA,)

但我不确定如何让这个函数遍历 map.list 中的所有子列表。我试图将它包装到一个 for 循环中,但它没有给我预期的结果:

for (i in seq_along(map.list)){
  each.map.list<- map.list[[i]]
  prot.list<- apply(seq.df, 1, function (x) lapply(each.map.list, function (y) substring(x, y, y)))
}

输出:

SPGL
SAPN
PFLD

我宁愿添加另一个 lapply 语句,但我不确定如何在 map.list 中指定每个列表

#this does not work, but something like: 
prot.list<- apply(seq.df, 1, function (x) lapply(map.list, function (y) lapply([[y]], function (z) substring(x, z, z)))

【问题讨论】:

    标签: r nested-loops lapply


    【解决方案1】:

    我们可以使用Map

    unlist(Map(function(x, y) paste(substring(x, unlist(y), 
          unlist(y)), collapse=""), seq.df[[1]], map.list))
    #[1] "THISPA" "GTAHL"  "PFLD"
    

    此外,我们可以在开始时执行单个 unlist 并使用扁平化的 list 作为输入,而不是 unlisting 两次

    l1 <- lapply(map.list, unlist)  
    sapply(Map(substring, seq.df[[1]], first = l1, last = l1), paste, collapse="")
    #[1] "THISPA" "GTAHL"  "PFLD"  
    

    或者使用map2 来自purrr

    library(purrr)
    map2_chr(seq.df[[1]], map.list, ~ str_c(substring(.x,
       unlist(.y), unlist(.y)), collapse=""))
    

    【讨论】:

      【解决方案2】:

      这是使用mapply()的解决方案

      它使用匿名函数,使用 seq.df 的字符分割字符串作为 x,位置列表作为 y。

      mapply( function(x,y) paste0( x[ unlist(y) ], collapse = "" ), 
              x = stringr::str_split( seq.df[,1], pattern = ""),
              y = map.list )
      
      [1] "THISPA" "GTAHL"  "PFLD"
      

      【讨论】:

        【解决方案3】:
        seq.df<- rbind.data.frame("MTHISPAVYGLWAIMSVLLAAFCAY",
                                  "MERSSAIVFPNVGTSVLSATIHLVGVTVLAHLISRRTALRGTST",
                                  "MLFEPFWCLLDLLRWSLDTHYIPAKRPLNGGGRSSNFD")
        map.list<- list(a<- list(2,3,4,5,6,7),
                        b<- list(13,14,30,31,32),
                        c<- list(5,6,10,11))
        lapply(1:nrow(seq.df), 
          function(x)paste(strsplit(as.character(seq.df[x,]), "")[[1]][unlist(map.list[[x]])], collapse=""))
        
        
        [[1]]
        [1] "THISPA"
        
        [[2]]
        [1] "GTAHL"
        
        [[3]]
        [1] "PFLD"
        

        【讨论】:

          猜你喜欢
          • 2015-12-16
          • 1970-01-01
          • 1970-01-01
          • 2018-09-15
          • 1970-01-01
          • 1970-01-01
          • 2019-03-03
          • 2013-03-08
          • 1970-01-01
          相关资源
          最近更新 更多