Search⌘ K
AI Features

Solution Review: Arrays and Matrices

Learn how to effectively create and manipulate arrays and matrices in R by reviewing solutions that use vectors and dimension arguments. Understand how to pass vectors to the array function and control matrix dimensions in R programming.

Solution #1: Using 33 vectors

R
myVector1 <- c ('a', 'b', 'c')
myVector2 <- c ('d', 'e', 'f')
myVector3 <- c ('g', 'h', 'i')
myArray <- array (c(myVector1, myVector2, myVector3), dim = c(3, 3, 1))
cat(myArray)

Explanation

Simply make three vectors and pass them to array(). Also, set the specific dimensions. Notice that the last argument to dim is 11 because we want just one matrix.

Solution #2: Using 11 vector

R
myVector <- c ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
myArray <- array (myVector, dim = c(3, 3, 1))
cat(myArray)

Explanation

We can also use only one vector, populate it, and pass it to array(). However, the dim argument remains the same because we want one 3x33x3 matrix.