What is the %||% operator?

I'm trying to create a custom ggplot2 geom by modifying geom_errorbar. The geom_errorbar function uses an operator that I've never seen before %||%, on line 37 here:

does anyone know what it is, and which package define it? Trying to run my custom geom I get the error:

Error in data$width %||% params$width %||% (resolution(data$x, FALSE) *  (from geom_errorbar2.R#40) : 
  could not find function "%||%"
1 Like

%||% is an operator from rlang to that lets you replace the default value for NULL.

From rlang docs:

This infix function makes it easy to replace NULLs with a default value. It's inspired by the way that Ruby's or operation (||) works.

It takes arguments x and y, where if x is NULL, will return y; otherwise returns x.

x %||% y

The reason your code doesn't work (I assume, from your snippet above) is because you need to import the function %||% in order to use it.

You can see the Specifying imports and exports section of Writing R Extensions, or the Namespace section of the R Packages book for more detail.

5 Likes

thank you very much for the very informative answer! I'm able to run my custom geom by loading the rlang package.

2 Likes