【问题标题】:Subset a symbol object in R在 R 中设置符号对象的子集
【发布时间】:2021-02-22 08:04:45
【问题描述】:

我想在过滤的时候总结一些数据。

它适用于声明的变量,但我不使用符号。

错误是: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 日创建

【问题讨论】:

    标签: r dplyr rlang


    【解决方案1】:

    由于运算符优先级,目前您的代码被解释为!!(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 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-10
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      相关资源
      最近更新 更多