You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在fabletools::autoplot.tbl_ts()中正确解引用字符变量?

在fabletools::autoplot.tbl_ts()中解引用字符向量的替代方法

问题背景

在dplyr中使用字符向量解引用变量时,通常可以通过!!运算符实现:

library(dplyr)
library(rlang)
library(tibble)

my_var <- "mpg"
my_data <- as_tibble(mtcars)

my_data |>
  select(!!my_var)

但在fabletools::autoplot.tbl_ts()中直接使用!!解引用字符向量无法得到预期结果:

library(testthat)
set.seed(12345)
df <- tsibble::tsibble(
  qtr = tsibble::yearquarter("2010 Q1") + 0:59,
  y = rnorm(60),
  index = qtr
)
dv_name <- "y"

actual <- fabletools::autoplot(df, !!dv_name)
expected <- fabletools::autoplot(df, y)
expect_equal(actual, expected)
#> Error: `actual` not equal to `expected`

解决方案

方法1:将字符向量转为符号后解引用

使用rlang::sym()把字符串转换为变量符号,再结合!!解引用:

actual <- fabletools::autoplot(df, !!rlang::sym(dv_name))
expect_equal(actual, expected) # 不再报错

方法2:使用.data代词

利用tidyverse的.data代词直接引用字符向量对应的变量:

actual <- fabletools::autoplot(df, .data[[dv_name]])
expect_equal(actual, expected) # 不再报错

原因说明

dplyr::select()可以直接接受字符串作为列名,但fabletools::autoplot.tbl_ts()的参数期望的是变量符号(而非字符串)。直接使用!!dv_name传递的是字符串值,而非对应的变量,因此需要先将字符串转换为符号,或通过.data代词直接映射到变量。

内容的提问来源于stack exchange,提问作者11rchitwood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:56:12