When using mutate-across, I have understood that the .names
argument may be used to name the output columns. If the desired column names are simply a truncation of the original names, how does one perform the truncation? In the example below, I have used rename_with
to achieve the desired outcome and I am wondering if the .names
argument could be directly tweaked to produce the same result.
df <- mtcars %>% head(5) %>% dplyr::select(am, wt_mtcars = wt , qsec_mtcars=qsec)
df
wt_mtcars qsec_mtcars
Mazda RX4 2.620 16.46
Mazda RX4 Wag 2.875 17.02
Datsun 710 2.320 18.61
Hornet 4 Drive 3.215 19.44
Hornet Sportabout 3.440 17.02
df %>%
mutate (across (contains("mtcars"), ~ .*10, .names = "{col}_1")) %>% ## perform a meaningless operation in .fns
rename_with(~str_remove(., "_mtcars_1"), contains("_mtcars_1"))
am wt_mtcars qsec_mtcars wt qsec
Mazda RX4 1 2.620 16.46 26.20 164.6
Mazda RX4 Wag 1 2.875 17.02 28.75 170.2
Datsun 710 1 2.320 18.61 23.20 186.1
Hornet 4 Drive 0 3.215 19.44 32.15 194.4
Hornet Sportabout 0 3.440 17.02 34.40 170.2