Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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)

like image 796
cxz2001 Avatar asked Sep 17 '25 23:09

cxz2001


1 Answers

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
like image 119
Dmitry Zotikov Avatar answered Sep 19 '25 17:09

Dmitry Zotikov