Lists and data frames

Named lists, data frames (tables), selecting rows and columns, sorting with order(), adding columns and aggregate().

Runs in Zerethon IDE · R 4.5 Official R documentation ↗
main.R
person <- list(name = "Ada", age = 36, langs = c("R", "Python"))
cat(sprintf("%s %g %d\n", person$name, person[["age"]], length(person$langs)))

people <- data.frame(
  name = c("bob", "amy", "eve"),
  age = c(25, 31, 28)
)
print(nrow(people))
print(people[order(-people$age), ])
print(people[people$age > 26, "name"])
people$senior <- people$age > 30
print(people)
print(aggregate(age ~ senior, data = people, FUN = mean))

Output

Ada 36 2
[1] 3
  name age
2  amy  31
3  eve  28
1  bob  25
[1] "amy" "eve"
  name age senior
1  bob  25  FALSE
2  amy  31   TRUE
3  eve  28  FALSE
  senior  age
1  FALSE 26.5
2   TRUE 31.0
  • A list can hold values of any type; x$name and x[["name"]] read one element, x["name"] returns a smaller list.
  • A data frame is a list of columns of the same length. df[rows, columns] selects; leave a side empty for “all”.
  • order() returns the row positions in sorted order; - sorts descending for numbers.
  • The numbers on the left of a printed data frame are row names, kept from the original rows.