Is there a way to code exists('x'), !is.null(x), and !is.na(x) checks a bit cleaner or elegantly?

# Works, but the ifs are repetitive
if (exists('x')) {
  if (!is.null(x)) {
    if (!is.na(x)) {
      print(y)
    }
  }
}

# Fatal error if x does not exist due to is.null(x) and is.na(x) checks
# if (exists('x')) should return FALSE and be done, but it does not
if (exists('x') & !is.null(x) & !is.na(x)) { print(y) }

Is there a way to do this more elegantly, maybe something akin to function(x) {y}?

Use the && operator. It stops at the first FALSE.

if (exists('x') && !is.null(x) && !is.na(x)) { print(y) }
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.