如何按顺序连接对象列表中的每个第 n:(nth+j) 个对象

How to sequentially concatenate every nth:(nth+j) object in a list of objects

我希望连接我拥有的对象列表中的每个 nth:nth(+jth) 个对象。更具体地说,我希望将每两个对象连接起来。 下面是相关列表的一小部分示例。

list("SRR1772151_1.fastq", "SRR1772151_2.fastq", "SRR1772152_1.fastq", 
    "SRR1772152_2.fastq", "SRR1772153_1.fastq", "SRR1772153_2.fastq")

我想从中创建一个看起来更接近这个的新列表。

list(c("SRR1772151_1.fastq", "SRR1772151_2.fastq"), c("SRR1772152_1.fastq", 
"SRR1772152_2.fastq"), c("SRR1772153_1.fastq", "SRR1772153_2.fastq"
))

我已经进行了以下尝试,但我的 for 循环没有成功。

for (i in seq(1,36, 2)) {
  for (j in 1:18) {
    unlist(List1[i:i+1]) -> List2[[j]]
  }
}

如有任何帮助或建议,我们将不胜感激。

您可以将其分为两个问题 -- 拆分列表,例如,

elts = split(lst, 1:2)

并连接元素

Map(c, elts[[1]], elts[[2]])

但我认为最好遵循 'tidy' 数据实践并创建具有分组因子的单个向量

df = data.frame(fastq = unlist(x), grp = 1:2, stringsAsFactors = FALSE)

或更具描述性

df = data.frame(
    fastq = unlist(lst),
    sample = factor(sub("_[12].fastq", "", unlist(lst))),
    stringsAsFactors = FALSE
)

最好使用整齐的数据,因为可以做到事半功倍,例如请注意,在使用列表时,您必须了解 split()Map() 以及 c() ,而使用矢量和 data.frames 你不需要!

这是使用数据帧的另一种尝试。输出是一个列表。

library(tidyverse)

data.frame(X1 = unlist(my_list), stringsAsFactors = F) %>% 
  group_by(str_sub(X1,1,10)) %>% # assuming first 10 characters forms the string
  summarise(list_value=list(X1)) %>% 
  pull(list_value)

对于一般情况,您可以创建大小为 j 的连续组向量,其中:

ceiling(seq_along(x) / j)

… 然后使用 tapply() 连接这些组中的所有元素。与使用 Map() 不同,如果块大小不等分列表的长度,这也将起作用。

x <- list("SRR1772151_1.fastq", "SRR1772151_2.fastq", "SRR1772152_1.fastq",
    "SRR1772152_2.fastq", "SRR1772153_1.fastq", "SRR1772153_2.fastq")

tapply(x, ceiling(seq_along(x) / 2), unlist)
#> $`1`
#> [1] "SRR1772151_1.fastq" "SRR1772151_2.fastq"
#> 
#> $`2`
#> [1] "SRR1772152_1.fastq" "SRR1772152_2.fastq"
#> 
#> $`3`
#> [1] "SRR1772153_1.fastq" "SRR1772153_2.fastq"
tapply(x, ceiling(seq_along(x) / 4), unlist)
#> $`1`
#> [1] "SRR1772151_1.fastq" "SRR1772151_2.fastq" "SRR1772152_1.fastq"
#> [4] "SRR1772152_2.fastq"
#> 
#> $`2`
#> [1] "SRR1772153_1.fastq" "SRR1772153_2.fastq"

reprex package (v0.2.1)

于 2019-06-12 创建