Skip to content
R

Data Frames

Create, inspect, filter, mutate, sort, aggregate, and merge data frames.

By EZ4Code Team
data-frametable

Code

# Create a data frame
df <- data.frame(
  id = 1:4,
  name = c("Alice", "Bob", "Carol", "Dave"),
  age = c(30, 25, 35, 28),
  score = c(88.5, 92.0, 76.5, 84.0),
  stringsAsFactors = FALSE
)

# Inspect
print(str(df))
print(summary(df))
print(head(df, 2))

# Select columns
print(df[, c("name", "score")])
print(df$name)

# Filter rows
print(df[df$age > 28, ])
print(subset(df, score >= 85, select = c(name, score)))

# Add and modify columns
df$grade <- ifelse(df$score >= 85, "A", "B")
df$age_next <- df$age + 1
print(df)

# Sort
df_sorted <- df[order(df$score, decreasing = TRUE), ]
print(df_sorted)

# Aggregate
agg <- aggregate(score ~ grade, data = df, mean)
print(agg)

# Merge
info <- data.frame(id = c(1, 2, 5), city = c("Paris", "Rome", "Lima"))
merged <- merge(df, info, by = "id", all.x = TRUE)
print(merged)

Explanation

A data frame is a list of equal-length columns that behaves like a table, with rows and columns addressable by index or name. subset, order, and aggregate provide compact idioms for filtering, sorting, and grouped summaries. merge joins two frames on shared key columns, mirroring SQL-style joins.

More R Snippets