These methods split an array and matrix into a list of arrays or matrices with the same number of dimensions according to the specified margin.

# S3 method for class 'array'
split(x, f, drop = FALSE, margin = NULL, ...)

# S3 method for class 'matrix'
split(x, f, drop = FALSE, margin = NULL, ...)

Arguments

x

A matrix or an array.

f, drop

See help for split(). Note that drop here is not for array dimensions: these are always preserved.

margin

Which margin of the array to split along. NULL splits as split.default, dropping dimensions.

...

Additional arguments to split().

Examples


x <- diag(5)
f <- rep(1:2, c(2,3))
split(x, f, margin=1) # Split rows.
#> $`1`
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    1    0    0    0    0
#> [2,]    0    1    0    0    0
#> 
#> $`2`
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    0    0    1    0    0
#> [2,]    0    0    0    1    0
#> [3,]    0    0    0    0    1
#> 
split(x, f, margin=2) # Split columns.
#> $`1`
#>      [,1] [,2]
#> [1,]    1    0
#> [2,]    0    1
#> [3,]    0    0
#> [4,]    0    0
#> [5,]    0    0
#> 
#> $`2`
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    1    0    0
#> [4,]    0    1    0
#> [5,]    0    0    1
#> 

# This is similar to how data frames are split:
stopifnot(identical(split(x, f, margin=1),
          lapply(lapply(split(as.data.frame(x), f), as.matrix), unname)))