転置の別の可能性は functionaperm
です。
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 を使用してもう 1 つの手順が必要です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