2015-11-10 26 views
2

我试图将一个参数作为字符传递给ggvis,但是我得到一个空的图。将参数传递给ggvis

重复的例子:

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() 

这是如何从以下不同的方法在LM()多数民众赞成在正常工作?

formula <- "mpg ~ cyl" 
mod1 <- lm(formula, data = mtcars) 
summary(mod1) 
#works 

由于

+0

如果变量的名称是字符串,则可以使用'prop'。它可能看起来像:'mtcars%>%ggvis(prop(“x”,as.name(y [1])),prop(“y”,as.name(y [2])))' – aosmith

+0

Haven'之前用过'prop',谢谢。 – Xlrv

回答

0

lm情况下,字符串将在内部强制转换为类式对象。 ~运算符是创建此公式对象的。

在第二种情况下,ggvis需要两个单独的公式,用于参数xy。在你的情况下,你只有一个很长的字符串,如果在逗号分隔(但这个长字符串本身不是一个公式),它可能被强制为两个单独的公式。

因此,ggvis功能将需要是这样为了工作:

#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() 

但是,这不会是做了非常有效的事情。