I'm building a function where users can select a column from a list of options, and within the function, I want to do an if statement where, if the x variable is one of the options that the function is designed to work with, it will generate the plot. Otherwise, it will print an error message.
However, when I try to do if({{x_variable}} == ses)--the correct variable in this example--I keep getting
Error in make_plot(test_data, x_variable = ses) : object 'ses' not found
That's the same error I get for if(enquo(x_variable) == ses) and if(!!x_variable == ses)
The correct answer will produce the plot when x_variable is ses and will print the error when x_variable is anything else.
Here's a sample dataset and my function (that does not work collectively, but each individual part does):
library(dplyr)
library(rlang) #if enquo() is needed
test_data <- tibble(ses = c(rep(c("High", "Mid", "Mid Low", "Low"), 2)),
total = c(10, 20, 20, 30, 9, 11, 40, 60))
make_plot <- function(data, x_variable) {
if({{x_variable}} == "ses") {
ggplot(data = test_data, aes(x = {{x_variable}}, y = total)) +
geom_col()
} else {
print("This function isn't designed for this variable, sorry!")
}
}
make_plot(test_data, x_variable = ses)
make_plot(test_data, x_variable = anything_else)

