在 R 中子集符号对象

Subset a symbol object in R

我想在筛选的同时总结一些数据。

它适用于声明的变量,但我没有成功使用符号。

错误是:object of type 'symbol' is not subsettable

我想找到解决这个问题的方法。

library(datasets)
library(magrittr)
library(dplyr)
#> 
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data(cars)
cars %<>% as_tibble()

test <- function (.data = NULL, x = NULL, y = NULL) {
  xs <- rlang::sym(x)
  ys <- rlang::sym(y)
  .data %>%
    summarise(
      sym_work = mean(!!xs),
      work = mean(dist[speed == 10]),
      not_work = mean(!!xs[!!ys == 10])
    )
}
test(.data = cars, x = "dist", y = "speed")
#> Error in xs[!!ys == 10]: objet de type 'symbol' non indiçable

reprex package (v0.3.0)

于 2020-11-10 创建

由于运算符优先级,目前您的代码被解释为 !!(xs[!!ys == 10]),这没有意义。你需要 (!!xs)[!!ys == 10] :

library(datasets)
library(magrittr)
library(dplyr)
#> Warning: package 'dplyr' was built under R version 3.6.3
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

data(cars)
cars %<>% as_tibble()

test <- function (.data = NULL, x = NULL, y = NULL) {
  xs <- rlang::sym(x)
  ys <- rlang::sym(y)
  .data %>%
    summarise(
      sym_work = mean(!!xs),
      work = mean(dist[speed == 10]),
      not_work = mean((!!xs)[!!ys == 10])
    )
}

test(.data = cars, x = "dist", y = "speed")
#> # A tibble: 1 x 3
#>   sym_work  work not_work
#>      <dbl> <dbl>    <dbl>
#> 1     43.0    26       26

reprex package (v0.3.0)

于 2020 年 11 月 10 日创建