Menu
Coddy logo textTech

Creating Matrices

Part of the Logic & Flow section of Coddy's R journey. Lesson 17 of 64.

A matrix is a vector arranged in rows and columns, and every value has the same type. matrix(data, nrow = ...) fills it column by column by default:

m <- matrix(1:6, nrow = 2)
print(m)

Output:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Add byrow = TRUE to fill it row by row, which matches data written one row per line:

m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(m)

Output:

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Give either nrow or ncol; R computes the other from the length of the data.

dim(m) returns the number of rows and columns, and nrow() and ncol() return each one alone. matrix(0, nrow = 2, ncol = 3) repeats a single value to fill the matrix:

m <- matrix(0, nrow = 2, ncol = 3)
print(dim(m))
print(nrow(m) * ncol(m))
print(length(m))

Output:

[1] 2 3
[1] 6
[1] 6

rbind() stacks vectors as rows and cbind() as columns, which builds a matrix from separate vectors:

a <- c(1, 2, 3)
b <- c(4, 5, 6)
print(rbind(a, b))
print(dim(cbind(a, b)))

Output:

  [,1] [,2] [,3]
a    1    2    3
b    4    5    6
[1] 3 2
challenge icon

Challenge

Easy

Complete make_grid(values, n_cols). Return a matrix with n_cols columns that holds values row by row. The number of values is always a multiple of n_cols.

The supplied code reads the values as a comma-separated line and n_cols from the next line. It prints each row of the returned matrix on its own line and then its size as rows x columns.

Try it yourself

make_grid <- function(values, n_cols) {
  # Write your code here
  matrix(values)
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
values <- as.numeric(strsplit(input[1], ",")[[1]])
m <- make_grid(values, as.numeric(input[2]))
for (i in seq_len(nrow(m))) cat(m[i, ], "\n")
cat(nrow(m), "x", ncol(m), "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler