R Data Frame Operations

Once you create or load a data frame, you need to query, sort, filter, update, and summarize it. These operations are what transform raw data into useful insights. This topic covers the most essential operations using base R.

Sorting a Data Frame

students <- data.frame(
  name  = c("Priya","Arjun","Zara","Kiran","Dev"),
  score = c(88, 75, 92, 65, 80),
  age   = c(21, 23, 20, 22, 24)
)

# Sort by score ascending
students[order(students$score), ]

# Sort by score descending
students[order(-students$score), ]

# Sort by age, then by score
students[order(students$age, students$score), ]

Filtering Rows

# Students scoring above 80
high_scorers <- students[students$score > 80, ]

# Multiple conditions
top_young <- students[students$score > 80 & students$age < 22, ]

# Using subset() (cleaner syntax)
subset(students, score > 75 & age < 23)

Selecting and Renaming Columns

# Select specific columns
students[, c("name", "score")]

# Rename a column
names(students)[names(students) == "score"] <- "marks"

# Rename using colnames()
colnames(students)[2] <- "marks"

Adding and Modifying Columns

students$grade   <- ifelse(students$marks >= 80, "A", "B")
students$bonus   <- students$marks * 0.05
students$total   <- students$marks + students$bonus

Removing Rows with Missing Values

df <- data.frame(
  x = c(1, NA, 3, NA, 5),
  y = c("a","b",NA,"d","e")
)

# Remove any row with at least one NA
clean_df <- na.omit(df)

# Check for NAs
is.na(df)
colSums(is.na(df))   # count NAs per column

Aggregating / Summarizing

sales <- data.frame(
  region  = c("North","South","North","East","South","East"),
  product = c("A","A","B","B","A","B"),
  revenue = c(1000,1500,800,1200,1100,900)
)

# Mean revenue by region
aggregate(revenue ~ region, data = sales, FUN = mean)

# Sum revenue by region and product
aggregate(revenue ~ region + product, data = sales, FUN = sum)

Output (aggregate by region):

  region  revenue
1   East   1050.0
2  North    900.0
3  South   1300.0

Merging Two Data Frames

customers <- data.frame(
  id   = c(1, 2, 3, 4),
  name = c("Asha","Balu","Cena","Devi")
)

orders <- data.frame(
  id     = c(1, 2, 2, 3),
  amount = c(500, 300, 700, 200)
)

# Inner join — only matching rows
merge(customers, orders, by = "id")

# Left join — all customers, matching orders
merge(customers, orders, by = "id", all.x = TRUE)

Reshaping: Wide to Long

wide <- data.frame(
  student = c("Ana","Bob"),
  math    = c(85, 90),
  english = c(78, 88)
)

long <- reshape(wide,
  direction   = "long",
  varying     = c("math","english"),
  v.names     = "score",
  timevar     = "subject",
  times       = c("math","english")
)

Apply Functions to Data Frame Columns

num_cols <- students[, sapply(students, is.numeric)]

# Mean of all numeric columns
sapply(num_cols, mean)

# Summary statistics
sapply(num_cols, function(x) c(mean=mean(x), sd=sd(x), max=max(x)))

These base R operations handle most common data tasks. In the dplyr topics ahead, you will learn a cleaner, more readable syntax for the same operations — but understanding base R data frame operations first gives you a solid foundation that works everywhere without loading extra packages.

Leave a Comment

Your email address will not be published. Required fields are marked *