R Advanced Introduction
R Advanced is the deeper pass over the beginner and intermediate ground. It builds on matrices, data frames and the apply family.
A matrix and its row totals
The matrix holds two rows of values. rowSums adds each row into one total for that row.
m <- matrix(c(4, 8, 2, 6), nrow = 2, byrow = TRUE)
print(m)
print(rowSums(m))A mean for a frame column
The frame pairs three names with three scores. mean averages the score column into one value.
scores <- data.frame(name = c("Ana", "Bo", "Cy"), score = c(88, 92, 79))
print(scores)
print(mean(scores$score))Apply over rows and columns
apply with margin 1 totals each row. apply with margin 2 averages each column.
m <- matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, byrow = TRUE)
print(apply(m, 1, sum))
print(apply(m, 2, mean))Example
sales <- matrix(c(12, 18, 9, 21, 14, 16), nrow = 2, byrow = TRUE)
print(sales)
print(rowSums(sales))
teams <- list(red = c(5, 10), blue = c(20, 30))
print(lapply(teams, sum))Key points
- A matrix holds values in rows and columns with one shared type.
- rowSums reduces a matrix to one total for each row.
- apply runs one function over the rows or columns of a matrix.
- A data frame holds columns of different types side by side.
- lapply runs one function over each item of a list and returns a list.
In this example, one matrix holds sales for two rows and rowSums gives 39 and 51 for the rows. lapply then totals each team vector and returns the totals as a list.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· rdrr.io R Snippets
Exercise
What does lapply return when it runs a function over a list?