r语言 - 拆分列表,每n个元素并绑定,然后绑定切片



我想切片列表的每个n元素,cbind切片,然后rbind切片。

我可以用下面的代码(n = 10个元素,列表有30个元素长)做到这一点。我"手动"选择列表中的每10个元素,然后cbind这10个元素切片。然后我对这些cbind ed切片进行rbind处理。

然而,我认为plyrdplyrl*ply可能有一种方法,或者至少其中一些。对于初学者来说,我不知道如何选择列表中的每个n元素,并且似乎不知道找到这个答案的适当搜索词。

dl <- list(c(2L, 1L, 3L, 2L, 1L, 1L, 3L), c(1L, 1L, 2L, 1L, 1L, 2L, 
1L), c(1L, 1L, 2L, 2L, 3L, 3L, 3L), c(1L, 1L, 2L, 2L, 3L, 3L, 
3L), c(1L, 1L, 2L, 2L, 3L, 3L, 3L), c(1L, 1L, 2L, 2L, 3L, 3L, 
1L), c(1L, 1L, 2L, 2L, 3L, 3L, 3L), c(1L, 3L, 2L, 1L, 3L, 2L, 
1L), c(3L, 1L, 2L, 3L, 3L, 1L, 3L), c(3L, 2L, 1L, 1L, 3L, 3L, 
1L), c(1L, 1L, 2L, 2L, 2L, NA, NA), c(1L, 1L, 2L, 2L, 3L, NA, 
NA), c(1L, 1L, 2L, 2L, 3L, NA, NA), c(1L, 1L, 2L, 2L, 3L, NA, 
NA), c(1L, 1L, 2L, 2L, 3L, NA, NA), c(1L, 1L, 2L, 2L, 3L, NA, 
NA), c(1L, 1L, 2L, 2L, 3L, NA, NA), c(1L, 1L, 2L, 2L, 3L, NA, 
NA), c(1L, 1L, 2L, 2L, 3L, NA, NA), c(2L, 1L, 2L, 1L, 1L, NA, 
NA), c(2L, 3L, 1L, 2L, 1L, 2L, NA), c(1L, 1L, 2L, 2L, 1L, 3L, 
NA), c(1L, 1L, 2L, 2L, 3L, 3L, NA), c(1L, 1L, 2L, 2L, 3L, 3L, 
NA), c(1L, 1L, 2L, 2L, 3L, 3L, NA), c(1L, 1L, 2L, 2L, 3L, 3L, 
NA), c(1L, 1L, 2L, 2L, 3L, 3L, NA), c(1L, 1L, 2L, 2L, 3L, 3L, 
NA), c(1L, 1L, 2L, 2L, 3L, 3L, NA), c(1L, 1L, 2L, 2L, 3L, 3L, 
NA)) 
# slice list 'manually' cbind those slices
dl1 <- dl[1:10]
dl1.c <- do.call("cbind", dl1)
dl2 <- dl[11:20]
dl2.c <- do.call("cbind", dl2)
dl3 <- dl[21:30]
dl3.c <- do.call("cbind", dl3)
# rbind the cbind slices for result
ans <- as.data.frame(rbind(dl1.c, dl2.c, dl3.c)) # ans as df
# ans <- rbind(dl1.c, dl2.c, dl3.c)

Try

do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), length(dl)/10, labels = FALSE))))

最新更新