How to add a calculated column to a data frame in R
· 1 min read · Updated March 14, 2026 · beginner
r mutate dplyr data.table transformation
Adding calculated columns is a fundamental data transformation.
With dplyr
The mutate() function from dplyr makes this straightforward:
library(dplyr)
df <- df %>%
mutate(total_price = price * quantity)
You can add multiple columns at once:
df <- df %>%
mutate(
total_price = price * quantity,
discount = ifelse(total > 100, 0.1, 0),
final_price = total_price * (1 - discount)
)
With base R
Base R uses direct assignment:
df$total_price <- df$price * df$quantity
Or with transform():
df <- transform(df, total_price = price * quantity)
With data.table
The data.table package uses a compact syntax:
library(data.table)
dt[, total_price := price * quantity]