换位的另一种可能性是 function aperm
。
A <- array (1:27, c(3,3,3))
# aperm permute the dimensions in the given order
# here we want to permute dimension 1 and 2
# so the new order is 2-1-3 instead of 1-2-3
aperm(A, c(2,1,3))
, , 1
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
, , 2
[,1] [,2] [,3]
[1,] 10 11 12
[2,] 13 14 15
[3,] 16 17 18
, , 3
[,1] [,2] [,3]
[1,] 19 20 21
[2,] 22 23 24
[3,] 25 26 27
就将函数应用于每一层(比如你想将每一层乘以不同的值)而言,这是另一种可能性:
vec <- c(1,5,3)
lapply(seq_along(vec), function(x)A[,,x]*vec[x])
[[1]]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[[2]]
[,1] [,2] [,3]
[1,] 50 65 80
[2,] 55 70 85
[3,] 60 75 90
[[3]]
[,1] [,2] [,3]
[1,] 57 66 75
[2,] 60 69 78
[3,] 63 72 81
但是正如您所看到的,它创建了一个列表,因此它需要使用 function 多一步simplify2array
:
simplify2array(lapply(seq_along(vec),function(x)A[,,x]*vec[x]))
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 50 65 80
[2,] 55 70 85
[3,] 60 75 90
, , 3
[,1] [,2] [,3]
[1,] 57 66 75
[2,] 60 69 78
[3,] 63 72 81
或直接使用sapply
:
sapply(seq_along(vec), function(x)A[,,x]*vec[x], simplify="array")
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 50 65 80
[2,] 55 70 85
[3,] 60 75 90
, , 3
[,1] [,2] [,3]
[1,] 57 66 75
[2,] 60 69 78
[3,] 63 72 81