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 cbind
ed 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)
The simple list slicing has many applications and along with it many variations of list splitting also exists and can come to us to solve. One such problem can be to split K elements after every N values. Let’s discuss ways in which this particular problem can be solved.
The best way to split a Python list is to use list indexing, as it gives you huge amounts of flexibility. When shouldn’t you use the NumPy array_split () Function to split a list in Python?
# Split a Python List into Chunks using numpy import numpy as np a_list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] our_array = np.array (a_list) chunked_arrays = np.array_split (our_array, 3 ) chunked_list = [ list (array) for array in chunked_arrays] print (chunked_list) # Returns: [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
Try
do.call(mapply, c(cbind, split(dl, cut(seq_along(dl), length(dl)/10, labels = FALSE))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With