Menu
Coddy logo textTech

Indexing Matrices

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

m[i, j] is the value in row i and column j. Leave one side empty to take a whole row or column: m[i, ] is row i and m[, j] is column j.

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

Output:

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

The same indexes work on the left of <-, so a cell, a row or a column can be replaced:

m <- matrix(0, nrow = 2, ncol = 3)
m[1, 2] <- 5
m[2, ] <- c(7, 8, 9)
print(m)

Output:

     [,1] [,2] [,3]
[1,]    0    5    0
[2,]    7    8    9

Rows and columns can have names, set with rownames() and colnames(). Then a name works as an index:

sales <- matrix(c(3, 5, 2, 8), nrow = 2, byrow = TRUE)
rownames(sales) <- c("north", "south")
colnames(sales) <- c("jan", "feb")
print(sales["south", "feb"])
print(sales[, "jan"])

Output:

[1] 8
north south 
    3     2 

Vectors of indexes select a block of rows and columns at once:

m <- matrix(1:9, nrow = 3, byrow = TRUE)
print(m[1:2, 2:3])
print(m[c(1, 3), 1])

Output:

     [,1] [,2]
[1,]    2    3
[2,]    5    6
[1] 1 7
challenge icon

Challenge

Easy

Complete cell_report(m, r, c). Return three lines: Cell: with the value in row r and column c, Row: with the values of row r, and Column: with the values of column c. Separate values with single spaces.

The supplied code reads a matrix from one line: rows are separated by ; and the values of a row by ,, so 1,2;3,4 is a matrix with the rows 1 2 and 3 4. The next two lines hold r and c. The code prints each returned line.

Try it yourself

cell_report <- function(m, r, c) {
  # Write your code here
  c("Cell: ", "Row: ", "Column: ")
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
parse_matrix <- function(line) {
  rows <- strsplit(line, ";")[[1]]
  matrix(as.numeric(unlist(strsplit(rows, ","))), nrow = length(rows), byrow = TRUE)
}
cat(cell_report(parse_matrix(input[1]), as.numeric(input[2]), as.numeric(input[3])), sep = "\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