Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of quosures using purrr

Tags:

r

purrr

tidyeval

Is it possible to return a list of quosures using purrr?

foo <- c(1:3)
purrr::map(foo, rlang::quo(. + 2))

Returns the evaluated quosures (ie. a list containing 3 to 5).

Is there a way to return a list containing quo(1 + 2), quo (2 + 2) etc.?

(Package versions if significant or this is visited in the future: purrr 0.2.5, rlang 0.2.1).

like image 987
Andrew Hill Avatar asked Mar 06 '23 16:03

Andrew Hill


1 Answers

You can use !! to unquote the input into a quosure:

foo <- c(1:3)
purrr::map(foo, ~ rlang::quo(!!.x + 2))
#> [[1]]
#> <quosure>
#>   expr: ^1L + 2
#>   env:  0000000015213C98
#> 
#> [[2]]
#> <quosure>
#>   expr: ^2L + 2
#>   env:  0000000015217758
#> 
#> [[3]]
#> <quosure>
#>   expr: ^3L + 2
#>   env:  00000000157B9FD0

Note that here we also use the formula shorthand for an anonymous function in map() to return an unevaluated quosure. Quosures themselves can be coerced into functions by map() (using purrr::as_mapper()), so the reason why you were getting evaluated answers in the first place because you were essentially writing map(foo, ~ . + 2).

Created on 2018-08-06 by the reprex package (v0.2.0.9000).

like image 96
Mikko Marttila Avatar answered Mar 20 '23 15:03

Mikko Marttila