R R

R: Data Frames

What you will learn

Data frames are R's version of a spreadsheet or SQL table — rows are observations, columns are variables. This is the most common data structure for real data analysis.

Creating a data frame

df <- data.frame(
    name = c("Alice", "Bob", "Charlie"),
    age = c(25, 30, 35),
    student = c(TRUE, FALSE, TRUE)
)

Accessing data

df$name              # "Alice" "Bob" "Charlie" (column as vector)
df[1, ]              # first row (all columns)
df[1, "age"]        # 25 (single value)
df[, "name"]        # entire name column
df[df$age > 28, ]    # rows where age > 28 (filtering)

Exploring a data frame

head(df)             # first 6 rows
str(df)              # structure: types, dimensions
summary(df)          # summary statistics per column
nrow(df)             # number of rows
ncol(df)             # number of columns
names(df)            # column names

Built-in datasets for practice

R comes with several built-in datasets you can use immediately:

data()               # list all available datasets
data(mtcars)         # load the mtcars dataset
head(mtcars)         # view first few rows
summary(mtcars)      # summary statistics

Common mistakes

  • Forgetting that df$col returns a vector, but df["col"] returns a data frame (single column).
  • Using df[1] (returns first column as data frame) vs df[, 1] (returns first column as vector).
  • Strings in data.frame automatically become factors — use stringsAsFactors = FALSE to prevent this.
  • Using $ with a column name stored in a variable — use df[[var]] instead.

Quick check below!