R Mutate and Arrange

Mutate adds new columns or transforms existing ones. Arrange sorts the rows. Both operations preserve all existing data while reshaping it for analysis. These are two of the most frequently used verbs in any dplyr pipeline.

mutate() — Adding and Transforming Columns

library(dplyr)

sales <- data.frame(
  product  = c("Laptop","Phone","Tablet","Watch","Earphones"),
  price    = c(65000, 25000, 35000, 15000, 4000),
  units    = c(10, 45, 20, 60, 100),
  discount = c(0.10, 0.05, 0.08, 0.15, 0.20)
)

Add New Columns

sales |> mutate(
  revenue        = price * units,
  discount_amt   = price * discount,
  final_price    = price - discount_amt,
  profit_margin  = revenue * 0.20
)

Conditional Column with ifelse()

sales |> mutate(
  category = ifelse(price > 20000, "Premium", "Budget"),
  hot_item = units > 50
)

Conditional Column with case_when()

sales |> mutate(
  price_band = case_when(
    price < 10000               ~ "Low",
    price >= 10000 & price < 40000 ~ "Mid",
    price >= 40000              ~ "High"
  )
)

Modify an Existing Column

sales |> mutate(
  price = price * 1.05    # 5% price increase
)

mutate() with across() — Apply to Multiple Columns

sales |> mutate(
  across(c(price, units), as.numeric)     # convert to numeric
)

# Apply rounding to all numeric columns
sales |> mutate(
  across(where(is.numeric), \(x) round(x, 2))
)

transmute() — Keep Only New Columns

# Like mutate() but drops original columns
sales |> transmute(
  product,
  revenue = price * units
)
#   product  revenue
# 1  Laptop   650000
# 2   Phone  1125000
# ...

arrange() — Sorting Rows

# Ascending (default)
sales |> arrange(price)

# Descending
sales |> arrange(desc(price))

# Multiple columns: sort by category then by revenue
sales |>
  mutate(revenue = price * units) |>
  arrange(category, desc(revenue))

Sorting with NA Values

# NAs go to the bottom by default
df <- data.frame(x=c(3,NA,1,NA,2))
arrange(df, x)
#    x
# 1  1
# 2  2
# 3  3
# 4 NA
# 5 NA

# Put NAs first
arrange(df, desc(is.na(x)), x)

Full Pipeline Example

sales |>
  mutate(
    revenue  = price * units,
    net_rev  = revenue * (1 - discount),
    category = ifelse(price > 20000, "Premium", "Budget")
  ) |>
  arrange(category, desc(net_rev)) |>
  select(product, category, price, units, net_rev)

Output:

   product category price units    net_rev
1   Budget     ...
2  Premium     ...

Mutate builds the derived features your analysis needs — revenue from price and units, categories from thresholds, age groups from birth years. Arrange puts data in the order that makes patterns visible. Together they transform raw data into analysis-ready form.

Leave a Comment

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