determine if value passed to function is a variable

Viewed 54

Short version: How can a function differentiate between receiving these two inputs?

value <- "asdf"
"asdf"

A reproducible example: Say I have a function that looks for evil, or at least for the string "evil"

library(stringr)

Find_Evil <- function(x) {
  x <- str_to_lower(x)
  if(str_detect(x, "evil")) {
    message("Evil detected")
  } else {
    return(x)
  }
}

The function works fine in detecting the presence of "evil" in its input.

Find_Evil("this has some evil in it")
Evil detected

What if I also want to detect whether or not a variable name has evil in it? This gets through when it shouldn't.

sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
[1] "sounds good but isn't"

I can check a variable name using deparse(substitute()) but how do I check to see if something is a variable first? What I'd like is something along the lines of the meta-code below (doesn't work):

Find_Evil <- function(x) {
  x <- str_to_lower(x)
  if (x is a variable) { # this is the part I need help on
    x_name <- str_to_lower(deparse(substitute(sneaky_evil))) # convert value name to string
    evil_name <- str_detect(x_name, "evil") # check name for evil
    evil_x <- str_detect(x, "evil") # check contents for evil
    if (sum(evil_name, evil_x) != 2) { # if either name or contents contains evil
      message("evil detected")
    } else {
      return(x)
    }
  } else {
    if (str_detect(x, "evil")) { # if x isn't a variable just check x (no name)
      message("Evil detected")
    } else {
      return(x)
    }
  }
2 Answers

Probably, something like this would help :

Find_Evil <- function(x) {
   var_type <- substitute(x)
   var_name <- deparse(substitute(x))
   if(grepl('evil', var_name) & is.name(var_type)) {
     return("evil detected in variable")
   }
   x <- tolower(x)
   if(grepl('evil', x)) {
     return("Evil detected in string")
   }
   else return(x)
}

sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
#[1] "evil detected in variable"

sneaky_only <- "sounds good but isn't"
Find_Evil(sneaky_only)
#[1] "sounds good but isn't"

sneaky_only <- "sounds good but evil"
Find_Evil(sneaky_only)
#[1] "Evil detected in string"

Find_Evil("sounds good but isn't")
#[1] "sounds good but isn't"

Find_Evil("sounds good but evil")
#[1] "Evil detected in string"

We can use

library(stringr)
Find_Evil <- function(x) {
   var_name <- deparse(substitute(x))
   if(str_detect(var_name, "evil")) {
     return("evil detected in variable")
   }
   x <- tolower(x)
   if(str_detect(x, 'evil')) {
     return("Evil detected in string")
   }
   else return(x)
 }

sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
#[1] "evil detected in variable"

sneaky_only <- "sounds good but isn't"
Find_Evil(sneaky_only)
#[1] "sounds good but isn't"


sneaky_only <- "sounds good but evil"
Find_Evil(sneaky_only)
#[1] "Evil detected in string"
Related