Data Frames
A data frame is R's table — rows and columns, with each column holding its own type — and it's the structure almost all of R's data-analysis tools are built around.
Building a data frame
R data-frame.R
students <- data.frame(
name = c("Ava", "Sam", "Lee"),
score = c(88, 92, 79)
)
students
Console
name score 1 Ava 88 2 Sam 92 3 Lee 79
data.frame() takes one or more equal-length vectors and lines them up as columns, automatically numbering the rows down the left side.
Accessing a column with $
R dollar-access.R
students$score mean(students$score)
Console
[1] 88 92 79 [1] 86.33333
students$score pulls out the score column as a plain vector, which is why you can hand it straight to mean().
Basic indexing with [row, column]
R bracket-indexing.R
students[1, ] students[, "name"]
Console
name score 1 Ava 88 [1] "Ava" "Sam" "Lee"
students[1, ] leaves the column position blank, meaning "every column" for row 1. students[, "name"] does the reverse — every row, just the name column.
Note: Selecting a single column with
[, "name"] drops it down to a plain vector, losing the data-frame structure — which surprises people expecting a one-column data frame back. Adding drop = FALSE, as in students[, "name", drop = FALSE], keeps it as a data frame instead.