rdplyr

Can dplyr::mutate function modify a column's value by the index of this column?


For example:

df = data.frame(A=c(1,2), B=c(3,4))
df %>% group_by(A) %>% mutate(.[[2]] = .[[2]] + 1)

This code will not run.

The code:

df %>% group_by(A) %>% mutate(B = .[[2]]+1)

can run. So I want to know if there is a way to replace 'B' with col's index(in this case,it's 2)


Solution

  • Use across:

    > df |> mutate(across(2, ~ .x + 1))
      A B
    1 1 4
    2 2 5
    

    With grouped dataframes, you'll need to adjust the index accordingly:

    > df |> group_by(A) |> mutate(across(1, ~ .x + 1))
    # A tibble: 2 × 2
    # Groups:   A [2]
          A     B
      <dbl> <dbl>
    1     1     4
    2     2     5