Checking if missing() and exists() in an if statement?

abc = data.frame(a = 1, b = 2)

double_check = function(x) {
  if (!missing(x)) {
    if (!exists(x)) {
      print('yay')
    }
  }
}

double_check(abc) # I need this to work
double_check(1)
double_check('abc') # Not this

I tried exists(as_string(x)), exists(as.name(x)) and other variants, but no luck.

Are you wanting a function that tests it has been given a data.frame ?
if so.

abc = data.frame(a = 1, b = 2)

double_check = function(x) {
  if (!missing(x)) {
   if (is.data.frame(x))
      print('yay')
  }
}

double_check(abc) # I need this to work
double_check(1)
double_check('abc')

No, I need to test if it exists() as an object.

but you want it to say no, if a string with its name is passed ?

perhaps:

abc = data.frame(a = 1, b = 2)

double_check = function(x) {
  x_ <- enexpr(x)
  if (!missing(x)) {
    if(exists(as.character(x_))){
      if(is.character(x))
         return(FALSE)
      return(TRUE)
    }}
  FALSE
}

double_check(abc) # TRUE
double_check(1)   # FALSE
double_check('abc') # FALSE
double_check(ab) # FALSE
double_check() # FALSE
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.