【问题标题】:Split list every n elements and cbind, then rbind slices每 n 个元素拆分列表并 cbind,然后 rbind 切片
【发布时间】:2015-10-17 20:35:59
【问题描述】:

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

我可以使用下面的代码来做到这一点(n = 10 个元素,列表长 30 个元素)。我“手动”选择列表中的每 10 个元素,然后 cbind 这 10 个元素切片。然后我rbind 那些cbinded 切片。

但是,我认为在plyrdplyr 中使用l*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)

【问题讨论】:

  • 也许do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), 3))))
  • 还有do.call(rbind, lapply(split(dl, rep(1:(length(dl)%/%10), each=10)), simplify2array))
  • @StevenBeaupré 这行代码会产生所需的输出。据我了解,这将是 3 个相等的部分(即 Levels: (0.971,10.7] (10.7,20.3] (20.3,30] 基于列表中元素的数量,将列表与这些切割分开,并将它们 cbind 到列表列表中,然后映射,“rbinds”这些列表。
  • 对于dplyr,以及您问题的第一部分,请参阅row_number -- dl %&gt;% group_by(row_number() %/% 10)。这将是在将 dl 转换为 data.frame 之后,可能通过data.frame(t(matrix(unlist(dl), 7)))

标签: r list dplyr rbind cbind


【解决方案1】:

试试

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

【讨论】:

    猜你喜欢
    • 2015-01-12
    • 2018-03-11
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多