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

时间:2019-06-27 19:17:58

标签: 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),
    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)))

3 个答案:

答案 0 :(得分:4)

我们可以使用Map

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

此外,我们无需在开头unlist进行两次操作,而是可以在开始时执行一个unlist,并使用展平的list作为输入

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=""))

答案 1 :(得分: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"

答案 2 :(得分:1)

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"
相关问题