If I want to use a character vector in dplyr, I can do this:
library(dplyr)
#>
#> 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
library(rlang)
library(tibble)
my_var <- "mpg"
my_data <- as_tibble(mtcars)
my_data |>
select(!!my_var)
Created on 2023-08-14 with reprex v2.0.2
Likewise, I want to do the same in 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`
Created on 2023-08-14 with reprex v2.0.2
Seems like the bang-bang !!
is not the right choice here. What should I do instead?
The problem is that dv_name
is a string, not a symbol. Use
fabletools::autoplot(df, .data[[dv_name]])
That will look up the string column name in the data. The .data
object is a special pronoun provided by rlang. The fact that this works with select()
is kind of specific to that function. You can use both
select(mtcars, mpg)
select(mtcars, "mpg")
But using a string for a column name doesn't work the same in most other functions.
you could also translate the string into a symbol and then use !!
. For example
fabletools::autoplot(df, !!rlang::ensym(dv_name))