How to apply a function to each row in R
· 2 min read · Updated March 14, 2026 · beginner
r iteration apply dplyr purrr
Applying a function to each row is a common task in R. Here are several ways to do it, from simple to more elegant.
With base R
The apply() function works on matrices and data frames:
df <- data.frame(
a = c(1, 2, 3, 4),
b = c(5, 6, 7, 8),
c = c(9, 10, 11, 12)
)
# Sum each row
row_sums <- apply(df, 1, sum)
# [1] 15 18 21 24
# Custom function
row_means <- apply(df, 1, function(x) mean(x))
# [1] 5 6 7 8
With dplyr and rowwise()
The dplyr package makes this readable:
library(dplyr)
df <- data.frame(
a = c(1, 2, 3, 4),
b = c(5, 6, 7, 8),
c = c(9, 10, 11, 12)
)
df %>%
rowwise() %>%
mutate(row_sum = sum(c_across(everything()))) %>%
ungroup()
With purrr
The purrr package provides functional programming tools:
library(purrr)
df <- data.frame(
a = c(1, 2, 3, 4),
b = c(5, 6, 7, 8)
)
# Using pmap
df %>%
mutate(row_max = pmap_dbl(., ~max(c(...))))
Using base R by()
The by() function splits data and applies functions:
df <- data.frame(
group = c("A", "A", "B", "B"),
value = c(10, 20, 30, 40)
)
by(df$value, df$group, sum)
Performance comparison
For large data frames, dplyr::rowwise() is often the clearest, while apply() can be faster for very large datasets. The purrr family gives you type safety.
See Also
- apply() — Apply functions over array margins
- lapply() — Apply a function to list or vector
- dplyr-mutate — Create new columns