简体   繁体   中英

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]]) ="

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]])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM