[英]How can I make an array of two matrices with a vector?
從包含元素 1 到 20 的向量生成一個由兩個 3X4 矩陣組成的數組。按列填充。
以上是我要解決的問題。 我試過的是下面的代碼,
y <- array(1:20, dim = c(3,4,2))
print(y)
它似乎有效。 如何在這里定義按列填充? 另外,如何使用單個向量添加名稱? 通常應該至少有兩個這樣的向量,
result <- array(c(vector1, vector2), dim = c(3,3,2))
This is introductory R, the OP should read An Introduction to R , file R-intro.pdf, that comes with every installation of R.
為了按列填充矩陣,沒有什么特別要做的,R 已經按列優先順序填充它們。
請注意3*4*2 == 24
並且由於只接受1:20
的值,因此最后 4 個值被回收。
y <- array(1:20, dim = c(3,4,2))
dimnames(y) <- list(paste("row", 1:3, sep = "_"),
paste("col", 1:4, sep = "_"),
paste("matrix", 1:2, sep = "_"))
y
#, , matrix_1
#
# col_1 col_2 col_3 col_4
#row_1 1 4 7 10
#row_2 2 5 8 11
#row_3 3 6 9 12
#
#, , matrix_2
#
# col_1 col_2 col_3 col_4
#row_1 13 16 19 2
#row_2 14 17 20 3
#row_3 15 18 1 4
現在該列按第三維求和。
apply(y, 3, colSums)
# matrix_1 matrix_2
#col_1 6 42
#col_2 15 51
#col_3 24 40
#col_4 33 9
以及每個矩陣的平均值。
apply(y, 3, mean)
#matrix_1 matrix_2
# 6.50000 11.83333
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.