Subsetting and Cleaning
Column Selection
Picking Fields
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 = "")
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 colspeoplenames_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 colspeoplelabel ← Ada
2names_only <- people["name"]3label <- names_only$name[1]4cat(label, "\n", sep = "")values this stepAdalabelAdanames_only$name[1]cat(label, " ", sep = "")
3label <- names_only$name[1]4cat(label, "\n", sep = "")outputAdavalues this stepAdalabel
Follow the Column
peoplestarts with name, age, and city columns.- The rows are Ada age
36in Paris and Lin age28in Lima. people["name"]keeps only thenamecolumn.names_only$name[1]reads the first name.- 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.