Get startedGet started for free

Creating Matrices in R

Matrices can be created and analyzed in a few different ways in R.

One way is to create the matrix yourself. There are a few different ways you can do this.

The matrix(a, nrow = b, ncol = c) command in R creates a matrix that repeats the element a in a matrix with b rows and c columns.

A matrix can be manually created by using the c() command as well.

This exercise is part of the course

Linear Algebra for Data Science in R

View Course

Exercise instructions

  • The command matrix(1, nrow = 2, ncol = 3) creates a 2 by 3 matrix of 1's. Create a 3 by 2 matrix of 2's and print the result.

  • The command matrix(c(1, 2, 3, 2), nrow = 2, ncol = 2, byrow = FALSE) creates a 2 by 2 matrix by superimposing the vectors c(1,2) and c(3,2) as columns. Change byrow to equal TRUE and print the result.

  • A 2 by 2 matrix of 1's (called A) is provided for you. Add this matrix to the previous matrix using the + command.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create two matrices of all 1's and all 2's that are 2 by 3 and 3 by 2, respectively
matrix(1, nrow = 2, ncol = 3)

print(matrix(___, nrow = 3, ncol = ___))

# Create a matrix B and change the byrow designation.
B <- matrix(c(1, 2, 3, 2), nrow = 2, ncol = 2, byrow = FALSE)
B <- matrix(c(1, 2, 3, 2), nrow = 2, ncol = 2, byrow = ___)

# Add A to the previously-created matrix B
A + ___
Edit and Run Code