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

SyntaxWhat It Returns
df$ageThe age column as a plain vector
df[, "age"]The age column as a plain vector
df["age"]The age column as a one-column data frame
df[1, ]The entire first row
df[1, 2]The single value in row 1, column 2

Selecting and Filtering

employees$name
employees[employees$age > 30, ]
employees[, c("name", "department")]
Note: Filtering rows with a logical condition — like employees$age > 30 — is one of the most common data frame operations. The condition produces a TRUE/FALSE value for every row, and only the TRUE rows survive the filter.

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?