将字符串转换为 R/ggplot2 中的函数参数的最佳方法?
Best way to convert character strings in to function arguments in R/ggplot2?
我正在开发一个闪亮的应用程序,用户可以在其中选择可以使用 ggplot2 绘制哪些变量,但是我完全不确定将字符串(即要绘制的变量的名称)转换为到合适的函数参数。
考虑以下非常人为的工作示例:
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' 变量?
下面是我想出来的,但是有没有更简单更常规的方法呢?请注意我在 aes() 和 facet_wrap() 函数中使用的不同方法。
x.var <- "gp"
ggplot(df, aes(x=lol <- switch(x.var,"gp"=gp), y = y)) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
非常感谢任何见解!
如果您使用 aes_string
来指定您的 x
和 y
变量而不是 x=lol <- switch(x.var,"gp"=gp)
会更好,即使用以下内容:
ggplot(df, aes_string(x = x.var, y = 'y')) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
不幸的是,对于 facet_wrap
函数,您已经完成的可能是最佳方法。
我正在开发一个闪亮的应用程序,用户可以在其中选择可以使用 ggplot2 绘制哪些变量,但是我完全不确定将字符串(即要绘制的变量的名称)转换为到合适的函数参数。
考虑以下非常人为的工作示例:
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' 变量?
下面是我想出来的,但是有没有更简单更常规的方法呢?请注意我在 aes() 和 facet_wrap() 函数中使用的不同方法。
x.var <- "gp"
ggplot(df, aes(x=lol <- switch(x.var,"gp"=gp), y = y)) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
非常感谢任何见解!
如果您使用 aes_string
来指定您的 x
和 y
变量而不是 x=lol <- switch(x.var,"gp"=gp)
会更好,即使用以下内容:
ggplot(df, aes_string(x = x.var, y = 'y')) +
geom_point() + facet_wrap(as.formula(paste("~",x.var)))
不幸的是,对于 facet_wrap
函数,您已经完成的可能是最佳方法。