将字符串转换为R/ggplot2中的函数参数的最佳方法? [英] Best way to convert character strings in to function arguments in R/ggplot2?
问题描述
我正在开发一个闪亮的应用程序,用户可以选择使用ggplot2绘制哪些变量,但是我完全不确定将字符串(这是要绘制的变量的名称)转换为合适的最佳方法函数参数.
I am working on a shiny app where the user selects which variables might be plotted using ggplot2, however I am completely unsure about the best way to convert character strings (which are the names of the variable to be plotted) in to suitable function arguments.
考虑以下非常人为的可行示例:
Consider the following very artificial, working example:
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))
ggplot(df, aes(x = gp, y = y)) +
geom_point() + facet_wrap(~gp)
现在,如果我只拥有变量名的字符串,我该如何告诉ggplot在x轴上绘制'gp'变量?
Now, how would I tell ggplot to plot the 'gp' variable on the x axis, if all I have is a character string of the name of the variable?
我已经提出了以下建议,但是有没有更简单,更常规的方法?请注意我在aes()和facet_wrap()函数中使用的不同方法.
I have whipped up the following, but is there a simpler and more conventional method? Note the different approaches I use in the aes() and facet_wrap() functions.
x.var <- "gp"
ggplot(df, aes(x=lol <- switch(x.var,"gp"=gp), y = y)) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
任何见识都将不胜感激!
Any insight is greatly appreciated!
推荐答案
如果使用aes_string
而不是x=lol <- switch(x.var,"gp"=gp)
来指定x
和y
变量,那就更好了,即使用以下命令:
It would be much better if you used aes_string
to specify your x
and y
variables, instead of x=lol <- switch(x.var,"gp"=gp)
, i.e. use the following:
ggplot(df, aes_string(x = x.var, y = 'y')) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
不幸的是,对于facet_wrap
函数,您已经完成的操作可能是最佳方法.
Unfortunately, for the facet_wrap
function what you have already done is probably the optimal way.
这篇关于将字符串转换为R/ggplot2中的函数参数的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!