简体   繁体   English

将 arguments 的向量列表作为 quosures 传递给带有 purrr 和 rlang 的 function

[英]Pass a list of vectors of arguments as quosures to a function with purrr and rlang

Sorry for the numerous prepositions in the title.抱歉标题中有很多介词。 Similar to this question, I have a list of quosures/arguments I want to pass to a function like dplyr::count :这个问题类似,我有一个 quosures/arguments 列表,我想传递给 function,比如dplyr::count

library(rlang)
suppressPackageStartupMessages(library(dplyr))

q_list <- function(...) {
  enquos(...)
}

my_q_list <- q_list(
  c(cyl, sort = TRUE),
  c(cyl, gear, sort = TRUE)
)
my_q_list
#> <list_of<quosure>>
#> 
#> [[1]]
#> <quosure>
#> expr: ^c(cyl, sort = TRUE)
#> env:  global
#> 
#> [[2]]
#> <quosure>
#> expr: ^c(cyl, gear, sort = TRUE)
#> env:  global

Created on 2020-09-02 by the reprex package (v0.3.0.9001)reprex package (v0.3.0.9001) 创建于 2020-09-02

Using purrr and rlang, how do I pass and execute each quosure of this list to count(mtcars, ...)使用 purrr 和 rlang,我如何传递和执行此列表的每个 quosure 以count(mtcars, ...)

So the end result is identical to:所以最终结果是相同的:

suppressPackageStartupMessages(library(dplyr))
count(mtcars, cyl, sort = TRUE)
#>   cyl  n
#> 1   8 14
#> 2   4 11
#> 3   6  7
count(mtcars, cyl, gear, sort = TRUE)
#>   cyl gear  n
#> 1   8    3 12
#> 2   4    4  8
#> 3   6    4  4
#> 4   4    5  2
#> 5   6    3  2
#> 6   8    5  2
#> 7   4    3  1
#> 8   6    5  1

Created on 2020-09-02 by the reprex package (v0.3.0.9001)reprex package (v0.3.0.9001) 创建于 2020-09-02

The thing that makes this difficult is the use of c() here.使这变得困难的是c()在这里的使用。 We really need some sort of rlang object to hold your parameters.我们确实需要某种rlang object 来保存您的参数。 Here's an altered function to generate your list这是一个经过修改的 function 来生成您的列表

q_list <- function(...) {
  q <- enexprs(...)
  transenv <- new_environment(list(c=exprs))
  purrr::map(q, function(x) {
    eval_tidy(x, env = transenv)
  })
}

This takes your expressions and evaulates them treating c() like enexprs() .这需要你的表达式并评估它们像enexprs() ) 一样对待c() ) 。 Then you can inject those values into your function call然后你可以将这些值注入你的 function 电话

my_q_list <- q_list(
  c(cyl, sort = TRUE),
  c(cyl, gear, sort = TRUE)
)

purrr::map(my_q_list, ~eval_tidy(quo(count(mtcars, !!!.x))))

This would have been easier if you just make the expressions in a list without using c()如果您只是在不使用c()的情况下在列表中创建表达式,这会更容易

my_q_list <- list(
  exprs(cyl, sort = TRUE),
  exprs(cyl, gear, sort = TRUE)
)
purrr::map(my_q_list, ~eval_tidy(quo(count(mtcars, !!!.x))))

The sort can be outside sort可以在外面

library(purrr)
list(q_list(cyl), q_list(cyl, gear)) %>% 
  map(~ count(mtcars, !!! .x, sort = TRUE))
#[[1]]
#  cyl  n
#1   8 14
#2   4 11
3   6  7

#[[2]]
#  cyl gear  n
#1   8    3 12
#2   4    4  8
#3   6    4  4
#4   4    5  2
#5   6    3  2
#6   8    5  2
#7   4    3  1
#8   6    5  1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM