typestar

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

  1. rowwise is the escape hatch when vectorization will not do.
  2. c_across gathers several columns for one row.
  3. pmap from purrr is often faster for the same job.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Windows & rows, step 19 of 27 in dplyr.

← Previous Next →