james han
james han

Reputation: 1

How can I make an array of two matrices with a vector?

Generate an array of two 3X4 matrices from a vector containing the elements 1 through 20. Fill by column.

  1. Add suitable row names, column names and matrix names to the array.
  2. Using the apply function, find the sum of the column elements in the array.
  3. In one line of code, find the mean of each matrix in the array. Result should be a vector of two numbers, one for each matrix.

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

Answers (1)

Rui Barradas
Rui Barradas

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

Related Questions