7

I would like to slice every n elements of list, cbind the slice, and then rbind the slices.

I can do this with the code below (n = 10 elements, list is 30 elements long). I 'manually' select every 10 elements of the list and then cbind these 10 element slices. I then rbind those cbinded slices.

However, I think that there could be a way to this with l*ply in plyr or dplyr, or at least some of it. For starters, I do not now how to select every n elements of list, and don't seem to know the appropriate search term to find this answer.

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)
krads
  • 1,350
  • 8
  • 14
nofunsally
  • 2,051
  • 6
  • 35
  • 53
  • 2
    Maybe `do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), 3))))` – Steven Beaupré Jul 27 '15 at 15:32
  • 1
    also `do.call(rbind, lapply(split(dl, rep(1:(length(dl)%/%10), each=10)), simplify2array))` – Rorschach Jul 27 '15 at 15:49
  • 1
    @StevenBeaupré this line of code results in the desired output. For my understanding, this will 3 equal parts (i.e. `Levels: (0.971,10.7] (10.7,20.3] (20.3,30]` based on the no. of elements in the list, split list with by those cuts, and cbind them into a list of lists, then mapply, 'rbinds' those lists. – nofunsally Jul 27 '15 at 15:52
  • 1
    For `dplyr`, and the first part of your question, see `row_number` -- `dl %>% group_by(row_number() %/% 10)`. This would be after transforming dl to a data.frame, maybe via `data.frame(t(matrix(unlist(dl), 7)))` – user295691 Jul 27 '15 at 16:22

1 Answers1

6

Try

do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), length(dl)/10, labels = FALSE))))
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77