When I mutate
across
data, the columns selected by .cols
are replaced by the results of the mutation. How can I perform this operation whilst:
- Keeping the columns selected by
.cols
in the output - Appropriately & automatically renaming the columns created by
mutate
?
For example:
require(dplyr)
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
require(magrittr)
#> Loading required package: magrittr
set.seed(7337)
## Create arbitrary tibble
myTibble <- tibble(x = 1:10,
y = runif(10),
z = y * pi)
## I can mutate across these columns
mutate(myTibble, across(everything(), multiply_by, 2))
#> # A tibble: 10 x 3
#> x y z
#> <dbl> <dbl> <dbl>
#> 1 2 1.78 5.58
#> 2 4 0.658 2.07
#> 3 6 0.105 0.331
#> 4 8 1.75 5.50
#> 5 10 1.33 4.19
#> 6 12 1.02 3.20
#> 7 14 1.20 3.75
#> 8 16 0.00794 0.0250
#> 9 18 0.108 0.340
#> 10 20 1.74 5.45
## I can subsequently rename these columns
mutate(myTibble, across(everything(), multiply_by, 2)) %>%
rename_with(paste0, everything(), "_double")
#> # A tibble: 10 x 3
#> x_double y_double z_double
#> <dbl> <dbl> <dbl>
#> 1 2 1.78 5.58
#> 2 4 0.658 2.07
#> 3 6 0.105 0.331
#> 4 8 1.75 5.50
#> 5 10 1.33 4.19
#> 6 12 1.02 3.20
#> 7 14 1.20 3.75
#> 8 16 0.00794 0.0250
#> 9 18 0.108 0.340
#> 10 20 1.74 5.45
## But how can I achieve this (without the fuss of creating & joining an additional table):
# A tibble: 10 x 6
# x y z x_double y_double z_double
# <int> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 0.313 0.982 2 0.625 1.96
# 2 2 0.759 2.39 4 1.52 4.77
# 3 3 0.705 2.22 6 1.41 4.43
# 4 4 0.573 1.80 8 1.15 3.60
# 5 5 0.599 1.88 10 1.20 3.77
# 6 6 0.0548 0.172 12 0.110 0.344
# 7 7 0.571 1.80 14 1.14 3.59
# 8 8 0.621 1.95 16 1.24 3.90
# 9 9 0.709 2.23 18 1.42 4.46
# 10 10 0.954 3.00 20 1.91 5.99
Created on 2021-09-16 by the reprex package (v2.0.1)