To split a list in R, you can use the split
function or create sublists manually using list manipulation.
In this example,
numbers
with initial integer values.split
function to split the vector into groups based on a factor.split
function returns a list, where each element is a subgroup of the original vector.numbers <- c(1, 2, 3, 4, 5, 6, 7, 8)
subgroups <- split(numbers, factor(rep(1:3, each = 3)))
print(subgroups)
$`1` [1] 1 2 3 $`2` [1] 4 5 6 $`3` [1] 7 8
In this example,
numbers
with initial integer values.numbers <- c(1, 2, 3, 4, 5, 6, 7, 8)
chunk_size <- 3
chunks <- list()
for (i in seq(1, length(numbers), by = chunk_size)) {
chunks[[length(chunks) + 1]] <- numbers[i:min(i + chunk_size - 1, length(numbers))]
}
print(chunks)
[[1]] [1] 1 2 3 [[2]] [1] 4 5 6 [[3]] [1] 7 8
In this tutorial, we learned How to Split a List in R language with well detailed examples.