I'm trying to pass an argument as a character to ggvis, but I'm getting an empty plot.
Reproducible example:
library(ggvis)
y <- c("mpg", "cyl")
ing <- paste0("x = ~ ", y[1], ", y = ~ ", y[2])
#works as intended
mtcars %>% ggvis(x = ~ mpg, y = ~ cyl) %>%
layer_points()
#gives empty plot
mtcars %>% ggvis( ing ) %>%
layer_points()
How is this different from the following approach in lm() thats works fine?
formula <- "mpg ~ cyl"
mod1 <- lm(formula, data = mtcars)
summary(mod1)
#works
Thanks
In the lm
case the string will be coerced to a class formula object internally. The ~
operator is what creates this formula object.
In the second case, ggvis
requires two separate formulas for x
and y
arguments. In your case you only have a long string that could be coerced into two separate formulas if split on comma (but this long string is not a a formula on its own).
So, the ggvis
function would need to be something like this in order to work:
#split the ing string into two strings that can be coerced into
#formulas using the lapply function
ing2 <- lapply(strsplit(ing, ',')[[1]], as.formula)
#> ing2
#[[1]]
#~mpg
#<environment: 0x0000000035594450>
#
#[[2]]
#~cyl
#<environment: 0x0000000035594450>
#use the ing2 list to plot the graph
mtcars %>% ggvis(ing2[[1]], ing2[[2]]) %>% layer_points()
But that wouldn't be a very efficient thing to do.