Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created March 1, 2023 18:33
Show Gist options
  • Save jmbarbone/11df146868ce7dba0b0015553318cf28 to your computer and use it in GitHub Desktop.
Save jmbarbone/11df146868ce7dba0b0015553318cf28 to your computer and use it in GitHub Desktop.
rowwise operations in R
df <- palmerpenguins::penguins

bench::mark(
  rowwise = df |> 
    dplyr::rowwise() |> 
    dplyr::mutate(sum = sum(dplyr::c_across(c(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g)))) |> 
    dplyr::ungroup(),
  rowSums = df |> 
    dplyr::mutate(sum = rowSums(dplyr::select(df, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g))),
  mapply = df |> 
    dplyr::mutate(sum = mapply(sum, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g)),
  pmap_db = df |> 
    dplyr::mutate(sum = purrr::pmap_dbl(list(bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g), sum))
)
#> Warning: Some expressions had a GC in every iteration; so filtering is
#> disabled.
#> # A tibble: 4 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 rowwise       2.18s    2.18s     0.458    9.63MB     3.66
#> 2 rowSums     11.64ms  16.74ms    58.3    197.79KB     3.89
#> 3 mapply       5.78ms   9.28ms    96.0     34.77KB     6.00
#> 4 pmap_db      7.99ms  11.96ms    80.7    306.04KB     3.94

Created on 2023-03-01 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment