Home > Net >  In R, how do I get an if statement to recognize if input in double curly brackets is a certain value
In R, how do I get an if statement to recognize if input in double curly brackets is a certain value

Time:07-18

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)

CodePudding user response:

You have to use:

make_plot(test_data, x_variable = "ses")

or alternatively:

ses <- "ses"
make_plot(test_data, x_variable = ses)

This error means that the object ses is not declared.


If you want to be able to pass undeclared objects such as ses as an input, you could use substitute(x_variable) or deparse(substitute(x_variable))

make_plot <- function(data, x_variable) {
  #print(deparse(substitute(x_variable)))
  if(deparse(substitute(x_variable)) == "ses") {
    ggplot(data = test_data, aes(x = ses, y = total))  
      geom_col()
  } else {
    print("This function isn't designed for this variable, sorry!")
  }
}

enter image description here

This is non-standard evaluation however, so make sure this is indeed what you're after as it can lead to surprising behaviours.

This explains the difference between both options, from enter image description here

CodePudding user response:

To supplement @gaut's elaborate answer, or if it's easier for you to remember (or understand how {{ work), you would need the following to use the curly brackets.

names(select(data, {{x_variable}})) == "ses"

  • Related