简体   繁体   中英

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!

%||% 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM