What's a good way to replicate `rowwise()` within the `.by` argument of mutate()?

Instead of doing

.data |>
  dplyr::rowwise() |>
  dplyr::mutate(across("col", func))

it would be neat to do something with .by when a single-operation grouping is needed:

.data |>
  dplyr::mutate(across("col", func), .by = ???)

I was wondering about dplyr::row_number() here but the help for mutate() and dplyr_by says it needs to be a tidyselect column name specification not a function.

This reprex shows what is intended, but the example relies on knowing that the first column has unique values - if you wanted a rowwise calculation without necessarily knowing you have a key column like this, is there a way to pass this to .by?

x <- tibble::tibble(
  letters = letters[1:6],
  numbers = 1:6,
  srebmun = 6:1
)

x |>
  dplyr::rowwise() |>
  dplyr::mutate(numsum = sum(numbers, srebmun))
#> # A tibble: 6 × 4
#> # Rowwise: 
#>   letters numbers srebmun numsum
#>   <chr>     <int>   <int>  <int>
#> 1 a             1       6      7
#> 2 b             2       5      7
#> 3 c             3       4      7
#> 4 d             4       3      7
#> 5 e             5       2      7
#> 6 f             6       1      7

x |>
  dplyr::mutate(numsum = sum(numbers, srebmun), .by = letters)
#> # A tibble: 6 × 4
#>   letters numbers srebmun numsum
#>   <chr>     <int>   <int>  <int>
#> 1 a             1       6      7
#> 2 b             2       5      7
#> 3 c             3       4      7
#> 4 d             4       3      7
#> 5 e             5       2      7
#> 6 f             6       1      7

Created on 2023-06-20 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.