Context
We would like to know how subtract columns, two by two. Specifically, we want to subtract the columns of the dataframe as follow:
- the
u_2018
-u_2019
. - the
u_2019
-u_2020
. - the
u_2020
-u_2021
. - the
u_2021
-u_2022
.
We looked for a optimal solution in the several stackoverflow question posts, like this (How to subtract two columns using tidyverse mutate with columns named by external variables), but the only undesired approach achieved is datiled in the R code used section. The R session version is 4.2.0
and the dplyr
package version is 1.0.9
.
Input data in R session
> dat
# A tibble: 6 × 5
u_2018 u_2019 u_2020 u_2021 u_2022
<int> <int> <int> <int> <int>
1 90035 88015 76135 50725 16517
2 20 NA NA 13792 12793
3 555 620 15032 19309 6479
4 11171 11782 10281 8974 3901
5 NA 116896 40169 13191 3610
R code used
dat %>%
mutate(
diff_2018_2019 = u_2018 - u_2019,
diff_2019_2020 = u_2019 - u_2020,
diff_2020_2021 = u_2020 - u_2021,
diff_2021_2022 = u_2021 - u_2022)
Question
We would like to know the optimal solution to subtract two by two columns. Maybe one approach includes mutate_at()
or across
to obtain the differences between and save the subtraction in new columns.
Thanks in advance