1

I want to fill values into a multiple dimension array in R. I know how to implement them in a loop. See below

a <- array(seq(1, 8), dim = rep(2, 3))

Case 1

b <- a
for (i in seq(length = dim(a)[2]))
{
    for (j in seq(length = dim(a)[3]))
    {
        b[,i,j] <- b[,1,1]
    }
}

i.e - fill first column of first stratum in all other columns:

#, , 1
#
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    2
#
#, , 2
#
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    2

Case 2

b <- a
for (i in seq(length = dim(a)[2]))
{
    b[,i,] <- b[,1,]
}

i.e. fill first column of each strata in remaining columns of the strata:

#, , 1
#
#     [,1] [,2]
#[1,]    1    1
#[2,]    2    2
#
#, , 2
#
#     [,1] [,2]
#[1,]    5    5
#[2,]    6    6

Case 3

b <- a
for (i in seq(length = dim(a)[3]))
{
    b[,,i] <- b[,,1]
}

i.e. fill first strata contents into all other strata:

#, , 1
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#
#, , 2
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4

How could I vectorize it? Thanks for any suggestions.

0

1 Answer 1

4

Here are the generalizations of your for loops using index vectors.

a <- array(seq(1, 24), dim = 2:4)

# a couple of handy index vectors
s2 <- seq(length = dim(a)[2])
s3 <- seq(length = dim(a)[3])

Case 1

B  <-  b <- a
for (i in seq(length = dim(a)[2]))
{
    for (j in seq(length = dim(a)[3]))
    {
        b[,i,j] <- b[,1,1]
    }
}


B[,s2,s3] <- B[,1,1]
identical(B,b)

Case 2

B  <-  b <- a
for (i in seq(length = dim(a)[2]))
{
    b[,i,] <- b[,1,]
}

# this is the tricky one.  The assignment works
# because we perumte the the matrix B so that we're 
# assigning to the last index.
B<- aperm(B,c(1,3,2)) 
B[,,s2] <- B[,,1]
B<- aperm(B,c(1,3,2)) 
identical(B,b)

Case 3

B  <-  b <- a
for (i in seq(length = dim(a)[3]))
{
    b[,,i] <- b[,,1]
}

B[,,s3] <- B[,,1]
identical(B,b)
Sign up to request clarification or add additional context in comments.

1 Comment

Case 1 and Case 3 could just be a[] <- a[,1,1] and a[] <- a[,,1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.