5

我想将 4 维数组转换为 2 维数据集。我提供了两种方法的代码:一种方法使用涉及的蛮力方法,cbind第二种rbind方法使用嵌套的for-loops. 不过,我认为可能有更好的方法。感谢您的任何建议。

R <- 3    # regions
M <- 5    # sites
J <- 2    # samples
T <- 4    # years

# 4-dim example array

y <- array(NA, dim = c(M, J, T, R))

# region 1
y[,1,1,1] =  1; y[,2,1,1] =  2; 
y[,1,2,1] =  3; y[,2,2,1] =  4; 
y[,1,3,1] =  5; y[,2,3,1] =  6;
y[,1,4,1] =  7; y[,2,4,1] =  8;

# region 2
y[,1,1,2] =  9; y[,2,1,2] = 10; 
y[,1,2,2] = 11; y[,2,2,2] = 12; 
y[,1,3,2] = 13; y[,2,3,2] = 14;
y[,1,4,2] = 15; y[,2,4,2] = 16;

# region 3
y[,1,1,3] = 17; y[,2,1,3] = 18; 
y[,1,2,3] = 19; y[,2,2,3] = 20; 
y[,1,3,3] = 21; y[,2,3,3] = 22;
y[,1,4,3] = 23; y[,2,4,3] = 24;

# desired two-dimensional data set

z = read.table(text = "
 1  2  3  4  5  6  7  8
 1  2  3  4  5  6  7  8
 1  2  3  4  5  6  7  8
 1  2  3  4  5  6  7  8
 1  2  3  4  5  6  7  8
 9 10 11 12 13 14 15 16
 9 10 11 12 13 14 15 16
 9 10 11 12 13 14 15 16
 9 10 11 12 13 14 15 16
 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
", sep = "", header = FALSE)

# using cbind and rbind to convert 4-dimensional array to 2-dimensional data set

r1 <- cbind(y[,,1,1], y[,,2,1], y[,,3,1], y[,,4,1])
r2 <- cbind(y[,,1,2], y[,,2,2], y[,,3,2], y[,,4,2])
r3 <- cbind(y[,,1,3], y[,,2,3], y[,,3,3], y[,,4,3])

my.data <- rbind(r1,r2,r3)
my.data

# using nested for-loops to convert 4-dimensional array to 2-dimensional data set

m2 <- matrix(NA, nrow = M*R, ncol= J*T)

for(i in 1:R) {
for(j in 1:T) {

m2[(M*(i-1) + (1:M)), (J*(j-1) + (1:J))] = y[,,j,i]

}
}

m2

# basis for nested for-loops above

m3 <- matrix(NA, nrow = M*R, ncol= J*T)

m3[(M*0 + (1:M)), (J*0 + (1:J))] = y[,,1,1]
m3[(M*0 + (1:M)), (J*1 + (1:J))] = y[,,2,1]
m3[(M*0 + (1:M)), (J*2 + (1:J))] = y[,,3,1]
m3[(M*0 + (1:M)), (J*3 + (1:J))] = y[,,4,1]

m3[(M*1 + (1:M)), (J*0 + (1:J))] = y[,,1,2]
m3[(M*1 + (1:M)), (J*1 + (1:J))] = y[,,2,2]
m3[(M*1 + (1:M)), (J*2 + (1:J))] = y[,,3,2]
m3[(M*1 + (1:M)), (J*3 + (1:J))] = y[,,4,2]

m3[(M*2 + (1:M)), (J*0 + (1:J))] = y[,,1,3]
m3[(M*2 + (1:M)), (J*1 + (1:J))] = y[,,2,3]
m3[(M*2 + (1:M)), (J*2 + (1:J))] = y[,,3,3]
m3[(M*2 + (1:M)), (J*3 + (1:J))] = y[,,4,3]

m3
4

2 回答 2

9

尝试了几次,但是:

matrix(aperm(y,c(1,4,2,3)),15)

或更一般地说

matrix(aperm(y,c(1,4,2,3)),prod(dim(y)[c(1,4)]))
于 2012-12-03T02:01:52.970 回答
0

如果有人来这里寻找关于折叠到数组的类似问题,但对于大于维度 = 2 的数组,请使用 array() 而不是 matrix(),并使用 dim() 参数指定您想要的维度。也适用于上述问题的代码是:

array(aperm(y,c(1,4,2,3)), dim=c(15,8))

如果您希望输出为 3d 数组,则可以通过在 dim() 中添加一个附加值来轻松修改此设置。对于您的特定情况,可能不需要 aperm() 位,但您应该始终检查折叠数组是否符合您想要的顺序并相应地使用 aperm()。

于 2016-12-02T21:28:54.903 回答