5

使用 调用下面的函数foo(c("b"))。输出显示为内联。

什么是正确的写作方式df %>% filter(!!x > (!!x))

我已经包含了一个使用mutatetidyeval 样式的示例,以将其与filter.

foo <- function(variables) {

  x <- rlang::sym(variables[[1]])

  print(x)
  #> b

  print(typeof(x))
  #> [1] "symbol"

  df <- data_frame(a = 1, b = 2)

  print(df %>% mutate(!!x := 100 + !!x))

  #> # A tibble: 1 x 2
  #>         a     b
  #>       <dbl> <dbl>
  #>   1     1   102  

  print(df %>% filter(!!x  > (!!x)))

  #> Error in !x : invalid argument type

  print(df %>% filter(magrittr::is_greater_than(!!x, !!x)))

  #> # A tibble: 0 x 2
  #> # ... with 2 variables: a <dbl>, b <dbl>

}
4

4 回答 4

3

除了一个小错字之外,您大部分时间都在那里,您的过滤器语句中的圆括号应该在变量上而不是值上。

print(df %>% filter((!!x) > !!x))

#> # A tibble: 0 x 2
#> # ... with 2 variables: a <dbl>, b <dbl>
于 2017-09-07T03:28:17.610 回答
2

编辑:所有这些都不再适用。优先级树被重新组织,以便!!x + !!yetc 默认做正确的事情。从 rlang 0.2.0 开始,括号不再是必需的。


The ! operator has really low precedence. This means that it will apply to most of the expression appearing on its right.

!! x > 3

is implicitly equivalent to:

(!! x > 3)

So you have to help R figure out the right precedence with explicit parentheses:

(!! x) > 3

Note that in most cases if you're unquoting on both sides of an operator, you technically don't have to apply the parentheses on the last one:

(!! x) + (!! y) + z

However that will vary according to often mysterious rules of precedence, so I suggest to always enclose in parentheses when operators are involved:

(!! x ) + (!! y) + (!! z)
于 2017-09-07T10:07:40.877 回答
0

您可以使用filter_at

oof <- function(variables) {
  x <- rlang::sym(variables[[1]])
  df <- data.frame(a = 1, b = 2)
  print(df %>% filter_at(vars(!!x), any_vars(. == !!x)))
  print(df %>% filter(magrittr::equals(!!x, !!x)))
}

我也magrittr::equals用来展示 magrittr 风格的作品

oof(c("b"))

#   a b
# 1 1 2
#   a b
# 1 1 2
于 2017-09-07T03:08:21.697 回答
0

This is a very generic way of handling any field value condition

data%>%
    filter(!!quo((!!as.name (field1)) > (!!myVal)))
于 2017-12-17T08:16:05.657 回答