Meta programming -- mutate and select multiple variables with a single object (of multiple column names) instead of calling multiple columns every time

variables = paste0('var1 + var2 + var3')

df_output |>
  mutate(vars = variables) |> # problem is with 'variables'
  select(-variables)

This saves one column of that exact string 'var1 + var2 + var3', but I would like it to add those variables var1 var2 and var3 into the column vars. What meta programming method do I need for it to recognise my intention?

Try this :

library(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
library(magrittr)

df = data.frame(
  var1=c(1,3,5),
  var2=c(3,2,1),
  var3=c(10,2,2)
)

myfunc <- function(e){
df %>%
  mutate(vars = {{e}})
}

myfunc(var1+var2-var3)
#>   var1 var2 var3 vars
#> 1    1    3   10   -6
#> 2    3    2    2    3
#> 3    5    1    2    4
Created on 2021-08-10 by the reprex package (v2.0.0)
1 Like
myfunc = function(e){
df |>
  mutate(vars = rowSums(across({{e}}))) |>
  select(-{{e}})
}

myfunc(c(var1, var2, var3))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.