I need to pass column names to the plotting function. The problem is that my column names are in the arguments and I don't know how to extract those as text.
Here is code that works, but I need to get the strings dynamically from the arguments.
create_plot <- function(df, group, subgroup, y){
var_group <- enquo(group)
var_subgroup <- enquo(subgroup)
var_y <- enquo(y)
df %>%
select(!!var_group, !!var_subgroup, !!var_y) %>%
mutate(!!var_group := as.factor(!!var_group),
!!var_subgroup := as.factor(!!var_subgroup)) %>%
ggsummarystats(., x = "COUNTRY", y="VALUE", # Need to get these from the arguments
palette = custom_pal,
ggfunc = ggboxplot,
color = "YEAR", #Same here
fill = "YEAR", #And here
summaries = c("n", "mean"))
}
create_plot(sales, YEAR, COUNTRY, VALUE)
Example using mtcars:
create_plot <- function(df, group, subgroup, y){
var_group <- enquo(group)
var_subgroup <- enquo(subgroup)
var_y <- enquo(y)
df %>%
select(!!var_group, !!var_subgroup, !!var_y) %>%
mutate(!!var_group := as.factor(!!var_group),
!!var_subgroup := as.factor(!!var_subgroup)) %>%
ggsummarystats(., x = "carb", y="mpg",
palette = custom_pal,
ggfunc = ggboxplot,
fill = "gear",
color = "gear",
summaries = c("n", "mean"))
}
create_plot(mtcars, gear, carb, mpg)
You can use rlang::as_name()
for that:
library(tidyverse)
library(rlang)
library(ggpubr)
create_plot <- function(df, group, subgroup, y){
var_group <- enquo(group)
var_subgroup <- enquo(subgroup)
var_y <- enquo(y)
df %>%
select(!!var_group, !!var_subgroup, !!var_y) %>%
mutate(
!!var_group := as.factor(!!var_group),
!!var_subgroup := as.factor(!!var_subgroup)
) %>%
ggsummarystats(
x = as_name(var_group),
y = as_name(var_y),
fill = as_name(var_subgroup),
ggfunc = ggboxplot,
summaries = c("n", "mean"))
}
create_plot(mtcars, gear, carb, mpg)
Created on 2021-06-14 by the reprex package (v1.0.0)