Split list every n elements and cbind, then rbind slices
Asked Answered
M

1

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)
Macdonald answered 27/7, 2015 at 15:13 Comment(4)
Maybe do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), 3))))Indeliberate
also do.call(rbind, lapply(split(dl, rep(1:(length(dl)%/%10), each=10)), simplify2array))Enneastyle
@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.Macdonald
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)))Linehan
U
6

Try

do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), length(dl)/10, labels = FALSE))))
Unwilling answered 27/7, 2015 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.