OneBite.Dev - Coding blog in a bite size

split an array into smaller arrays in R

Code snippet on how to split an array into smaller arrays in R

split <- function(mylist, groupsize)
  lapply(1:ceiling(length(mylist)/groupsize), 
         function(x) mylist[(x-1)*groupsize + 1:groupsize])

This code creates a function called “split” which takes two arguments; mylist (the array to be split) and groupsize (the size of each of the smaller arrays). The code then uses lapply which is an R function for applying a function to each element of a list or vector. The argument inside lapply takes two parts; the first part indicates how many times the array shall be split using the ceiling function that rounds up from the division of the array length over the requested group size. The second part of the argument is the function that applies the split; it slices the list into smaller chunks of the requested group size. Finally, the function is returned.

r