2017-08-01 57 views
0

我有一些指定爲字符串的變量名稱(例如來自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)))) 

回答

2

的這兩種選項可能簡單:

my_summarise <- function(df, group_var) { 
    print(group_var) 

    df %>% 
    #Either works 
    group_by_at(.vars = group_var) %>% 
    #group_by(!!sym(group_var)) %>% 
    summarise(a = mean(a)) 
} 

my_summarise(df,someString) 

my_plot <- function(df, group_var) { 
    print(group_var) 

    ggplot(data = df %>% 
      group_by_at(.vars = group_var) %>% 
      #group_by(!!sym(group_var)) %>% 
      summarise(a = mean(a)), 
     aes_string(x = group_var, y = "a")) + 
    geom_bar(stat = "identity") 
} 

my_plot(df, someString) 

...在這裏你可以使用任何group_bygroup_by_at

0

那麼打電話給my_summarise(df, as.name(someString))呢?