Search code examples
rlistsplitchunks

How to split list at every 10th item in R?


I have a list of 100 items. I want to split it after each 10th item in Code 1. Code 2 is about a list of two former lists and splitting it to 20 lists of 10 items each.

Code 1

Expected output: ten lists of 10 items.

A <- 100
a <- rnorm(A) # [1:100]
n <- 10
str(a)

# Not resulting in equal size of chunks with vectors so reject
# http://stackoverflow.com/a/3321659/54964
#d <- split(d, ceiling(seq_along(d)/(length(d)/n)))

# Works for vectors but not with lists
# http://stackoverflow.com/a/16275428/54964
#d <- function(d,n) split(d, cut(seq_along(d), n, labels = FALSE)) 

str(d)

Test code 2

Input: a list of two lists

aa <- list(a, rnorm(a))

Expected output: 20 lists of 10 item size

Testing Loki's answer

segmentLists <- function(A, segmentSize) {
  res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))

  #print(res)    
  res <- unlist(res, recursive = F)
}

segmentLists(aa, 10)

Output: loop going on, never stopping

OS: Debian 8.5
R: 3.3.1


Solution

  • you can use lapply.

    aa <- list(a, rnorm(a))
    aa
    n <- 10
    
    x <- lapply(aa, function(x) split(unlist(x), cut(seq_along(unlist(x)), n, labels = F)))
    y <- unlist(x, recursive = F)
    str(y)
    # List of 20
    # $ 1 : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
    # $ 2 : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
    # $ 3 : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
    # $ 4 : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
    # $ 5 : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
    # $ 6 : num [1:10] -0.115 0.164 -0.365 -1.827 -2.036 ...
    ...
    
    length(y)
    # [1] 20
    

    to remove the names of the list elements in y ($ 1, $ 2 etc.) you can use unname()

    str(unname(y))
    # List of 20
    # $ : num [1:10] 1.0895 -0.0477 0.225 -0.6308 -0.1558 ...
    # $ : num [1:10] -0.469 -0.381 0.709 -0.798 1.183 ...
    # $ : num [1:10] 0.757 -1.128 -1.394 -0.712 0.494 ...
    # $ : num [1:10] 1.135 0.324 0.75 -0.83 0.794 ...
    # $ : num [1:10] -0.786 -0.068 -0.179 0.354 -0.597 ...
    ...
    

    Using a function, you have to return res at the end of the function.

    segmentLists <- function(A, segmentSize)
    {
      res <- lapply(A, function(x) split(unlist(x), cut(seq_along(unlist(x)), segmentSize, labels = F)))
    
      #print(res)
    
      res <- unlist(res, recursive = F)
      res <- unname(res)
      res
    }