0

when programming using dplyr, to programmatically use variables in dplyr vers from function arguments, they need to be references by {{var}}

This works well, but I would like to use lapply with the var argument supplied in a list. This is throwing me an error. I have tried back and forth using substitute and rlang vars like sym but to no avail.

any suggestions? Thanks!

library(tidyverse)
tb <- tibble(a = 1:10, b = 10:1)

foo <- function(var, scalar){
  tb %>% mutate(new_var = {{var}}*scalar)
}

foo(a, pi) #works

lapply(X = list(
  list(sym("a"), pi),
  list(substitute(b), exp(1))), FUN = function(ll) foo(var = ll$a, scalar = ll$pi) ) #err

1 Answers1

1

You can get round the non-standard evalutation by naming the list elements and using do.call

lapply(X = list(
  list(var = sym("a"), scalar = pi),
  list(var = substitute(b), scalar = exp(1))), 
  FUN = function(ll) do.call(foo, ll))
#> [[1]]
#> # A tibble: 10 x 3
#>        a     b new_var
#>    <int> <int>   <dbl>
#>  1     1    10    3.14
#>  2     2     9    6.28
#>  3     3     8    9.42
#>  4     4     7   12.6 
#>  5     5     6   15.7 
#>  6     6     5   18.8 
#>  7     7     4   22.0 
#>  8     8     3   25.1 
#>  9     9     2   28.3 
#> 10    10     1   31.4 
#> 
#> [[2]]
#> # A tibble: 10 x 3
#>        a     b new_var
#>    <int> <int>   <dbl>
#>  1     1    10   27.2 
#>  2     2     9   24.5 
#>  3     3     8   21.7 
#>  4     4     7   19.0 
#>  5     5     6   16.3 
#>  6     6     5   13.6 
#>  7     7     4   10.9 
#>  8     8     3    8.15
#>  9     9     2    5.44
#> 10    10     1    2.72

Created on 2022-11-03 with reprex v2.0.2

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87