WJanousek - 1 year ago 70
R Question

# Create list of arrays by subsetting single array R

I have a large 4-dimensional array and would like to subset this array into a list where each element of the list is an array.

Data Example:

``````species<-c("Moose","Deer","Wolf","Bear","Livestock","Human")
unit<-c("A","B")
survey <-1:3
year<-1:3
data <- expand.grid(species=species, unit=unit, survey=survey, year=year)
data\$count <- round(rnorm(108,10,2),0)
library(reshape)
data.array <- cast(data, survey~year~unit~species)
``````

data.array has dimensions [3,3,2,6]

Looping over the 4th dimension to subset is where I've hit a wall. I would like to subset by the 4th dimension which in this example is "species". Specifically I would like to create a list of arrays for every two species. As such:

``````array.list <- list()
array.list[[1]] <- data.array[,,,1:2]
array.list[[2]] <- data.array[,,,3:4]
array.list[[3]] <- data.array[,,,5:6]
str(array.list)
``````

The full data set has a 4th dimension consisting of 111 species so a solution that can handle an odd number would be best.
Thanks!

We get the length of the 4th dimension ('n'), get the sequence of alternating elements ('i1'), create an 'array.list' of `length` 'i1'. Loop through the sequence of 'array.list' and assign each of the elements of 'array.list' with the subset of 'data.array' based on the index we created 'i1'.
``````n <- dim(data.array)[4]