[英]Add list-column of tibbles to a tibble based on a list-column of filter quosures without helper function
I have a list-column of filter quosures in a tibble, and I want to create another list-column of tibbles based on an existing tibble and the filter quosures:我在 tibble 中有一个过滤器 quosures 的列表列,我想根据现有的 tibble 和过滤器 quosures 创建另一个 tibble 列表列:
library(tidyverse)
t1 <- tibble(x = letters)
tibble(filters = quos(x == "a", x == "b")) %>%
mutate(dat = map(filters, ~filter(t1, !!.x)))
#> Error in local_error_context(dots = dots, .index = i, mask = mask): promise already under evaluation: recursive default argument reference or earlier problems?
This doesn't work as I expected, likely due to the interaction between map
, !!
这不像我预期的那样工作,可能是由于
map
之间的交互, !!
and .x
.和
.x
。
Using a helper function works as expected:使用助手 function 按预期工作:
helper_function <- function(dat_in, filters_quo_in) {
filter(dat_in, !!filters_quo_in)
}
tibble(filters = quos(x == "a", x == "b")) %>%
mutate(dat = map(filters, ~helper_function(t1, .x)))
#> # A tibble: 2 × 2
#> filters dat
#> <quos> <named list>
#> 1 x == "a" <tibble [1 × 1]>
#> 2 x == "b" <tibble [1 × 1]>
Is there any way to get my first attempt to work in tidyverse without using a helper function?有什么方法可以让我第一次尝试在 tidyverse 中工作而不使用助手 function? Or is there a better way to pass a list-column of filter-expressions to a tibble at the same time, and return the results as another list-column?
或者是否有更好的方法将过滤器表达式的列表列同时传递给 tibble,并将结果作为另一个列表列返回?
Created on 2022-10-11 with reprex v2.0.2创建于 2022-10-11,使用reprex v2.0.2
According to this thread https://community.rstudio.com/t/when-and-how-to-use-and-xy-pipe/101824/3根据这个线程https://community.rstudio.com/t/when-and-how-to-use-and-xy-pipe/101824/3
You're also currently trying to use the '.'
您目前还在尝试使用“。” to reference the data frame within the called function (after the ~) which won't work as you now have a different context - in a ~ function the '.'
引用名为 function(在 ~ 之后)中的数据框,这将不起作用,因为你现在有不同的上下文 - 在 ~ function 中 '.' now refers to the first argument
现在指的是第一个参数
This thread goes further.这个线程更进一步。 dplyr piping data - difference between `.` and `.x`
dplyr 管道数据 - `.` 和 `.x` 之间的差异
I found the answer in ?purrr::map
我在
?purrr::map
中找到了答案
If a formula, eg ~.x + 2, it is converted to a function. There are three ways to refer to the arguments:
如果一个公式,eg ~.x + 2,它被转换为一个function。可以通过三种方式引用arguments:
For a single argument function, use.
对于单个参数 function,请使用。
For a two argument function, use.x and.y
对于两个参数 function,使用.x 和.y
For more arguments, use..1, ..2, ..3 etc
如需更多 arguments,请使用 ..1、..2、..3 等
tibble(filters = quos(x == "a", x == "b")) %>%
mutate(dat = map(filters, ~filter(t1, ..1)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.