WJanousek 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:

survey <-1:3
data <- expand.grid(species=species, unit=unit, survey=survey, year=year)
data$count <- round(rnorm(108,10,2),0)
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]

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

Answer Source

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]
i1 <- seq(1, n, by = 2)

array.list <- vector("list", length(i1))
for(i in seq_along(array.list)){
  array.list[[i]] <- data.array[,,, i1[i]:pmin(i1[i]+1, n)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download