Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
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
Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.
Data Import/Export
Read and write CSV, TSV, RDS, RData, and text files with base R.