R / CHAPTER 05
Data frames and column structure
IntermediatePreserve rectangular data and its intended column types.
By the end of this chapter
- Construct named columns
- Select rows and columns deliberately
- Preserve a data frame when selecting one column
The idea
A data frame stores a rectangular collection of columns. Different columns may have different types, but they describe the same number of rows. Give columns meaningful names so calculations express the data model rather than unexplained numeric positions. The $ operator selects a named column, while two-dimensional bracket notation separates a row selection from a column selection with a comma.
Selecting a single column with brackets can simplify the result to a vector. Use drop = FALSE when downstream code requires a data frame regardless of the number of selected columns. Filtering rows should apply one logical decision per row, and missing values in that decision need an explicit policy. Creating a derived column makes the transformation visible without overwriting an original measurement prematurely.
tasks <- data.frame(name = c("A", "B", "C"), minutes = c(5, 12, 8))
tasks$double <- tasks$minutes * 2
chosen <- tasks[tasks$minutes >= 8, c("name", "double"), drop = FALSE]
cat(chosen$name, sep = ",")
cat("
")
cat(sum(chosen$double), "
", sep = "")B,C 40
Rows B and C meet the threshold. Selecting both named columns preserves their relationship, and their derived values twenty-four and sixteen sum to forty.
Try it yourself
Return a data frame containing only an id column for rows with positive known scores, preserving a data-frame result.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING