Babu
Babu

Reputation: 159

What does the %||% operator mean in R?

In the below R code snippet (taken from a debugger), what does the %||% operator mean, in line 8?

function (env = caller_env(), default = NULL) 
{
  out <- switch_type(env, environment = env, definition = , 
    formula = attr(env, ".Environment"), primitive = base_env(), 
    closure = environment(env), list = switch_class(env, 
      frame = env$env))

  out <- out %||% default

if (is_null(out)) {
    type <- friendly_type(type_of(env))
    abort(paste0("Can't extract an environment from ", type))
  }
  else {
    out
  }
}

Thanks for your help!

Upvotes: 0

Views: 72

Answers (1)

fmic_
fmic_

Reputation: 2446

%||% is not part of the R language. A quick search on GitHub for the code provided leads to the rlang package.

library(rlang)
`%||%`

leads to:

function (x, y) 
{
    if (is_null(x)) 
        y
    else x
}
<environment: namespace:rlang>

in other words, it returns the left side if it's not NULL and the right side otherwise.

This operator is widely used in the tidyverse.

Upvotes: 2

Related Questions