How to Apply Functions Row-Wise to Data Frames in R
Apply functions row-wise when you need to compute a value that depends on several columns within the same observation — a custom score, a conditional flag, or a string assembled from multiple fields. Before reaching for row-wise operations, check whether a vectorized expression works instead. mutate(df, z = x + y) is much faster than mutate(rowwise(df), z = sum(c_across(x:y))) because addition is already vectorized and operates on entire columns at once. Reserve row-wise iteration for cases where no vectorized equivalent exists, such as calling an external API, applying a model prediction, or evaluating a formula that changes per row.
The dplyr::rowwise() approach is the most readable when column names matter:
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()
For numeric matrices, base R apply(m, 1, f) is the fastest:
m <- matrix(1:12, nrow = 4, byrow = TRUE)
row_sums <- apply(m, 1, sum)
purrr::pmap() gives you type-safe output when the function interface is complex. Choose rowwise() for readability, apply() for speed on numeric data, and pmap() for flexibility with complex functions.
See also
- apply(), Apply functions over array margins
- lapply(), Apply a function to list or vector
- dplyr::mutate(), Create new columns