Search code examples
rsamplesub-array

Assigning different values to multiple subarrays


I have an array, x, with random values from 1:10 assigned to each subarray within x.

x <- array(sample(1:10), dim = c(5, 5, 2)) # 5 rows, 5 columns, 2 levels
x

This gives

x
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    6    7    6    7    6
[2,]    8    5    8    5    8
[3,]    9   10    9   10    9
[4,]    3    4    3    4    3
[5,]    2    1    2    1    2

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    7    6    7    6    7
[2,]    5    8    5    8    5
[3,]   10    9   10    9   10
[4,]    4    3    4    3    4
[5,]    1    2    1    2    1

In each subarray above sample(...) randomly selects values in 1:10 and assigns them to x.

Is there an existing R function that randomly assigns a proportion of values to each level of an array automatically? Say, only 1:2 to the first level, only values 8:9 the second level and only values 3, 4, 5, 6, 7, 10 to the third level.

I know how to do this with subsetting ([]), but subsetting becomes tedious when the number of levels is large (say 10 or more, instead of only 3 (as above)).


Solution

  • The abind library has the function abind that will help in doing what you want.

    I implemented a list with all of the desired ranges and then used that list to construct the new array with the third dimension. The along parameter tells abind to add in the third dimension.

    subsets <- list(c(1,2),c(8:10),c(3,4,5,6,7))
    # first array
    x <- array(sample(subsets[[1]],25,replace=T),dim=c(5,5))
    # 2:n arrays added to x
    for (i in 2:length(subsets)) {
        x <- abind(x,array(sample(subsets[[i]],25,replace=T),dim=c(5,5)),along=3)
    }