Data frames can be subset by column name. Selecting a column keeps the values aligned with their rows.

Program

Play the script to keep the name column and read its first value.

column_selection.R
Replay: real traced execution (multi-file project)
people <- data.frame(name = c("Ada", "Lin"), age = c(36, 28), city = c("Paris", "Lima"))
names_only <- people["name"]
label <- names_only$name[1]
cat(label, "\n", sep = "")
  1. people ← 2 rows x 3 cols

    1people <- data.frame(name = c("Ada", "Lin"), age = c(36, 28), city = c("Paris", "Lima"))2names_only <- people["name"]
    values this step2 rows x 3 colspeople
  2. names_only ← 2 rows x 1 col

    1people <- data.frame(name = c("Ada", "Lin"), age = c(36, 28), city = c("Paris", "Lima"))2names_only <- people["name"]3label <- names_only$name[1]
    values this step2 rows x 1 colnames_only2 rows x 3 colspeople
  3. label ← Ada

    2names_only <- people["name"]3label <- names_only$name[1]4cat(label, "\n", sep = "")
    values this stepAdalabelAdanames_only$name[1]
  4. cat(label, " ", sep = "")

    3label <- names_only$name[1]4cat(label, "\n", sep = "")
    outputAda
    values this stepAdalabel

Follow the Column

  1. people starts with name, age, and city columns.
  2. The rows are Ada age 36 in Paris and Lin age 28 in Lima.
  3. people["name"] keeps only the name column.
  4. names_only$name[1] reads the first name.
  5. The script prints Ada. | row | name | age | city | kept column | | --- | --- | --- | --- | --- | | 1 | Ada | 36 | Paris | Ada | | 2 | Lin | 28 | Lima | Lin |
column name `people["name"]` selects a column by name.
data frame subset Single-bracket column selection keeps a data frame result.
dollar access `names_only$name` reads one named column as a vector.

Exercise: column_selection.R

Reproduce the printed value Ada, then identify which selected column and row position produced it.