我有一些指定爲字符串的變量名稱(例如來自Shiny應用程序的輸入),我想在我的dplyr和ggplot2代碼中使用它們,就好像它們是變量一樣。dplyr 0.7 - 指定分組變量作爲字符串
我通過反覆試驗瞭解了它的工作原理,但我覺得必須有更好的方法。什麼是更好的方式來執行這些操作?
library(rlang)
library(ggplot2)
library(dplyr)
someString <- "g1"
df <- tibble(
g1 = c(1, 1, 2, 2, 2),
g2 = c(1, 2, 1, 2, 1),
a = sample(5),
b = sample(5)
)
my_summarise <- function(df, group_var) {
print(group_var)
df %>%
group_by(!!group_var) %>%
summarise(a = mean(a))
}
my_plot <- function(df, group_var) {
print(group_var)
ggplot(data = df %>%
group_by(!!group_var) %>%
summarise(a = mean(a)),
aes_string(x = quo_name(group_var), y = "a")) +
geom_bar(stat = "identity")
}
my_summarise(df, quo(UQ(sym(someString))))
my_plot(df, quo(UQ(sym(someString))))