Reputation: 1
Generate an array of two 3X4 matrices from a vector containing the elements 1 through 20. Fill by column.
Above is what I'm trying to solve. What I've tried is code below,
y <- array(1:20, dim = c(3,4,2))
print(y)
It seems like it works. How do I define fill by column here? Also, how can I add names using a single vector? Normally there should be at least two vectors like this,
result <- array(c(vector1, vector2), dim = c(3,3,2))
Upvotes: 0
Views: 977
Reputation: 76402
This is introductory R, the OP should read An Introduction to R, file R-intro.pdf, that comes with every installation of R.
In order to fill the matrices by column, there is nothing in particular to be made, R already fills them in column-major order.
Note that 3*4*2 == 24
and since only the values 1:20
are accepted, the last 4 values are recycled.
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
Now the column sums by 3rd dimension.
apply(y, 3, colSums)
# matrix_1 matrix_2
#col_1 6 42
#col_2 15 51
#col_3 24 40
#col_4 33 9
And the mean values of each matrix.
apply(y, 3, mean)
#matrix_1 matrix_2
# 6.50000 11.83333
Upvotes: 1