Row-wise work in R
rowwise turns each row into its own group, for calculations across columns.
library(dplyr)
scores <- tibble(
lang = c("r", "python"),
week1 = c(88, 104),
week2 = c(96, 99),
week3 = c(92, 101)
)
print(mutate(rowwise(scores),
best = max(c_across(starts_with("week"))),
mean = round(mean(c_across(week1:week3)), 1)))
print(mutate(scores, total = rowSums(across(starts_with("week")))))
print(ungroup(rowwise(scores)) |> nrow())
How it works
rowwiseis the escape hatch when vectorization will not do.c_acrossgathers several columns for one row.pmapfrom purrr is often faster for the same job.
Keywords and builtins used here
acrosscc_acrosslibrarymaxmeanmutatenrowprintroundrowSumsrowwisestarts_withtibbleungroup
The run, in numbers
- Lines
- 15
- Characters to type
- 350
- Tokens
- 122
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 70 seconds.
Step 2 of 3 in Windows & rows, step 19 of 27 in dplyr.