R Data Frames
A data frame is R's built-in table structure that stores columns of different data types side by side, making it the standard way to work with structured, real-world data.
What Is a Data Frame?
Think of a data frame as a spreadsheet living inside R. Each column can hold its own type of data — numbers, text, dates, or logical TRUE/FALSE values — but every column must have exactly the same number of rows. Under the hood, a data frame is actually a list of equal-length vectors, one vector per column, which is why building one from named vectors feels so natural.
Creating a Data Frame
employees <- data.frame(
name = c("Asha", "Ben", "Carla"),
age = c(29, 34, 41),
department = c("Sales", "IT", "HR")
)
print(employees)Inspecting a Data Frame
- nrow(df) counts the rows, and ncol(df) counts the columns
- dim(df) returns both at once, as c(rows, columns)
- names(df) (or colnames(df)) lists every column name
- str(df) shows the type and a preview of each column
- summary(df) prints quick statistics — min, max, mean, and more — for each column
Checking the Shape
dim(employees)
str(employees)
summary(employees)Selecting Rows and Columns
Selecting and Filtering
employees$name
employees[employees$age > 30, ]
employees[, c("name", "department")]Adding Columns and Rows
You can attach a brand-new column simply by assigning to a name that doesn't exist yet, for example employees$senior <- employees$age >= 35. To add a new row, build a one-row data frame with matching column names and combine it with rbind(employees, new_row). rbind() is strict about structure — it expects the same column names, in a compatible order, or it will throw an error.
Exercise: R Data Frames
What is a key difference between a data frame and a matrix in R?