I have a series of functions that make some ggplot2 charts.
I have a new dataset that I want to use these functions on, to make the charts.
This new dataset has its own unique names for the columns that the functions needs.
It is also likely that I will get additional new datasets (with their own different column names) in the future).
I was thinking of making a named vector where I specified the new dataset's column names to utilise (and also the name of the new dataset object itself), and I could give the values of this named vector to each of the functions.
Here is a minimally reproducible example for what I am talking about.
I know it is going to involve some combination of !!, enquo, sym... but I've tried heaps and it looks like it's got me beat.
Also, I would like to do this without altering the functions (i.e. I would still like to utilise the functions by entering in the dataset / column object names directly, as well).
library(tidyverse)
library(rlang)
# make a dataset
dif_data_name <- tibble(dif_col_name = 1:50)
# a function that only utilises a dataset
test_function_only_data <- function(dataset) {
dataset %>%
pull() %>%
sum()
}
# a function that utilises the dataset and a specific column
test_function_with_col <- function(dataset, only_column) {
only_column <- enquo(only_column)
dataset %>%
pull(!! only_column) %>%
sum()
}
# If I specify the datset object, this works
test_function_only_data(dif_data_name)
# so does this (with the column name as well)
test_function_with_col(dif_data_name, dif_col_name)
# But I was hoping to use a named vector for the dataset and column arguments
function_arguments <- c("dataset" = "dif_data_name",
"only_column" = "dif_col_name")
# These (below) do not work. But I would like to figure out how to make them work.
# first function test
test_function_only_data(
function_arguments[["dataset"]]
)
# second function test
test_function_with_col(function_arguments[["dataset"]],
function_arguments[["only_column"]])