Menu
Coddy logo textTech

Row and Column Summaries

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

rowSums() and rowMeans() return one result per row; colSums() and colMeans() one per column. Here each row is a student and each column a test:

scores <- matrix(c(80, 90, 70, 60, 75, 85), nrow = 2, byrow = TRUE)
print(rowMeans(scores))
print(colSums(scores))

Output:

[1] 80.00000 73.33333
[1] 140 165 155

For any other summary, apply(m, 1, f) calls f on every row and apply(m, 2, f) on every column:

scores <- matrix(c(80, 90, 70, 60, 75, 85), nrow = 2, byrow = TRUE)
print(apply(scores, 1, max))
print(apply(scores, 2, min))

Output:

[1] 90 85
[1] 60 75 70

Combine a summary with which.max() to find which row or column wins:

scores <- matrix(c(80, 90, 70, 60, 75, 85), nrow = 2, byrow = TRUE)
best_test <- which.max(colMeans(scores))
print(best_test)
print(round(rowMeans(scores), 1))

Output:

[1] 2
[1] 80.0 73.3

apply() also accepts a function you write on the spot with function(r). Here it counts the values above 5 in each row:

m <- matrix(c(3, 8, 1, 9, 2, 7), nrow = 2, byrow = TRUE)
print(apply(m, 1, function(r) sum(r > 5)))

Output:

[1] 1 2
challenge icon

Challenge

Easy

Complete class_report(scores). Each row of scores is a student and each column a test. Return one line per student, Student 1: 81.7, with the student's mean rounded to one decimal. Add a last line Best test: followed by the number of the column with the highest mean.

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 code prints each returned line.

Try it yourself

class_report <- function(scores) {
  # Write your code here
  character(0)
}

# 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(class_report(parse_matrix(input[1])), 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