R 列表列表上的嵌套apply语句

R 列表列表上的嵌套apply语句,r,nested-loops,lapply,R,Nested Loops,Lapply,我想提取seq.df(单列df)中与匹配map.list(列表列表)中的索引相匹配的蛋白质 示例数据: seq.df<- rbind.data.frame("MTHISPAVYGLWAIMSVLLAAFCAY", "MERSSAIVFPNVGTSVLSATIHLVGVTVLAHLISRRTALRGTST", "MLFEPFWCLLDLLRWSLDTHYIPAKRPLNGGGRSSNFD") map.list<- list(a<- list(2,3,4,5,6,7

我想提取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))
如果我只在map.list的第一个子列表上运行嵌套应用程序,我将得到我想要的第一个蛋白质:

prot.list<- apply(seq.df, 1, function (x) lapply(map.list[[1]], function (y) substring(x, y, y)))
我更愿意添加另一个lappy语句,但我不确定如何在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)))
#这不起作用,但类似于:

保护列表我们可以使用
Map

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

此外,我们可以在开始时执行一次
取消列表
,而不是两次取消列表
,并将该平铺的
列表
用作输入

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

seq.df这里有一个使用
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"
unlist(Map(function(x, y) paste(substring(x, unlist(y), 
      unlist(y)), collapse=""), seq.df[[1]], map.list))
#[1] "THISPA" "GTAHL"  "PFLD"
l1 <- lapply(map.list, unlist)  
sapply(Map(substring, seq.df[[1]], first = l1, last = l1), paste, collapse="")
#[1] "THISPA" "GTAHL"  "PFLD"  
library(purrr)
map2_chr(seq.df[[1]], map.list, ~ str_c(substring(.x,
   unlist(.y), unlist(.y)), collapse=""))
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"
mapply( function(x,y) paste0( x[ unlist(y) ], collapse = "" ), 
        x = stringr::str_split( seq.df[,1], pattern = ""),
        y = map.list )

[1] "THISPA" "GTAHL"  "PFLD"