Hi all,
I have to repeat many times some operations that iterates over many columns.
The data frame I need to work on contains thousands of columns .
Here is a simplified example:
library(magrittr)
library(tidyverse)
library(glue)
foo <- tibble(a1 = 1:2, b1 = 3:4, a2 = 5:6, b2 = 7:8)
for(i in 1:2) {
foo %<>%
mutate(!!sym(glue("ab{i}")) := !!sym(glue("a{i}")) + !!sym(glue("b{i}")))
}
foo
#> # A tibble: 2 x 6
#> a1 b1 a2 b2 ab1 ab2
#> <int> <int> <int> <int> <int> <int>
#> 1 1 3 5 7 4 12
#> 2 2 4 6 8 6 14
foo <- tibble(a1 = 1:2, b1 = 3:4, a2 = 5:6, b2 = 7:8)
This works very well and it is pretty efficient, but I wonder if I miss a high level function from {tidyselect}
or elsewhere doing that exact job?
I use the code to communicate with others and I find the syntax !!sym(glue( := !!sym(glue(
a little too intimidating for the folks I communicate with my folks...
Any suggestions?
I tried alternatives such as the following (which I failed to convert into a mutate_at) but I could not find anything convincing...
for(i in 1:2) {
foo %<>%
mutate(!!sym(glue("ab{i}")) := pmap_dbl(foo %>% select(num_range("a", i), num_range("b", i)), ~ sum(c(...))))
}
foo
#> # A tibble: 2 x 6
#> a1 b1 a2 b2 ab1 ab2
#> <int> <int> <int> <int> <dbl> <dbl>
#> 1 1 3 5 7 4 12
#> 2 2 4 6 8 6 14
Many thanks,
Alex