我想将值填充到R中的多维数组中。我知道如何在循环中实现它们。见下文
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]
}
}
即 - 填写所有其他列中第一层的第一列:
#, , 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,]
}
即。填充地层其余列中每个地层的第一列:
#, , 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]
}
即。将第一层的内容填入所有其他层:
#, , 1
#
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
#
#, , 2
#
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
我怎么能把它矢量化?谢谢你的任何建议。
答案 0 :(得分:4)
以下是使用索引向量的for循环的概括。
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])
<案例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)
<案例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)
<案例3
B <- b <- a
for (i in seq(length = dim(a)[3]))
{
b[,,i] <- b[,,1]
}
B[,,s3] <- B[,,1]
identical(B,b)