Guido Berning
Guido Berning

Reputation: 197

How to mutate several columns by column index rather than column name using across?

Building on this questions:

R dplyr mutate on column index

dplyr: how to reference columns by column index rather than column name using mutate?

I want to mutate several columns using column indexes for both the source and the destination of the mutate like:

df <- tribble(~C1,~C2,~C3,1,2,3,4,5,6,7,8,9)
dfn <- df
dfn[,1:2] = dfn[,3]   # like this in dplyr

df <- df %>% mutate(accross(.[[1:2]]) = .[[3]])

gives:

Fehler: Unerwartete(s) '=' in "df <- df %>% mutate(accross(.[[1:2]]) ="
Error: Unexpected '=' in "df <- df %>% mutate(accross(.[[1:2]]) ="

Upvotes: 4

Views: 4572

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270055

The first argument of across can specify the columns to use and set and the second is the function to use to transform them. The second argument to across could alternately be function(x) .[[3]] .

df %>% mutate(across(1:2, ~ cur_data()[[3]]))

giving:

# A tibble: 3 x 3
     C1    C2    C3
  <dbl> <dbl> <dbl>
1     3     3     3
2     6     6     6
3     9     9     9

These would also work and both run faster than the above with the last one being the fastest.

df %>% replace(1:2, .[[3]])

library(collapse)
df %>% ftransformv(1:2, function(x) .[[3]])

Upvotes: 3

tmfmnk
tmfmnk

Reputation: 40171

One option could be:

df %>% 
 mutate(across(1:2, ~ across(3) %>% pull()))

     C1    C2    C3
  <dbl> <dbl> <dbl>
1     3     3     3
2     6     6     6
3     9     9     9

Upvotes: 1

Related Questions