Reputation: 9816
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))
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
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
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.
Upvotes: 1
Views: 94
Reputation: 10167
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])
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)
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)
B <- b <- a
for (i in seq(length = dim(a)[3]))
{
b[,,i] <- b[,,1]
}
B[,,s3] <- B[,,1]
identical(B,b)
Upvotes: 4