Lesson 6 of 8 · 10 min

Data frames

A data frame is R's table: columns of equal length, where each column is a vector and each row is one record.

students <- data.frame(
  name  = c("Ana", "Tino", "Rudo"),
  age   = c(19, 21, 20),
  score = c(72, 88, 65)
)

nrow(students)        # 3
names(students)       # "name" "age" "score"
students$score        # 72 88 65   one column, as a vector
mean(students$score)  # 75

Adding columns

Assign to a new $ name; vectorised arithmetic fills every row:

students$passed <- students$score >= 70

Selecting rows and columns

df[rows, columns]. Leave a part empty to mean "all":

students[1, ]                        # the first row
students[, c("name", "score")]       # two columns, every row
students[students$age >= 20, ]       # rows matching a condition

Sorting

order() gives the row positions in sorted order; use them to reorder the rows:

students[order(students$score, decreasing = TRUE), ]

head(df) shows the first rows, and summary(df) summarises every column.

Your task

The starter has a data frame of farms.

  1. Add a column yield_per_ha: harvest (tonnes) divided by hectares.
  2. big_farms: the farms with 4 or more hectares.
  3. ranked: all farms ordered by yield per hectare, highest first.
script.R
farms <- data.frame(
  farm      = c("Moyo", "Dube", "Ncube", "Banda"),
  hectares  = c(4, 3, 10, 2),
  harvest_t = c(12, 6, 32, 8)
)

# 1. add yield_per_ha


# 2. big_farms


# 3. ranked

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…