3

Trying to learn something from source code. I stumbled upon "%||%" in ggplot2 as well as in rCharts. Obviously the latter does not import the former, nor does it define "%||%" as a function. How can I search my R ecosystem for these functions? OS X' spotlight seems not to be the easiest solution.

Can anybody explain what it does and point to where it's defined?

Matt Bannert
  • 27,631
  • 38
  • 141
  • 207

1 Answers1

5

In both of these cases, the function does the same thing.

Here it is from rCharts:

#' Set a default value for an object
#' 
#' This function sets the value of an object to a default value if it is not defined. 
#' @params x object
#' @params y object
#' @keywords internal
#' @noRd
`%||%` <- function(x, y){
  if (is.null(x)) y else x
}

Here it is from "ggplot2"--slightly different syntax but same operation:

ggplot2:::`%||%`
# function (a, b) 
# {
#     if (!is.null(a)) 
#         a
#     else b
# }

For finding the definitions of these functions, you can start by trying getAnywhere(). Here's the result on my system:

getAnywhere("%||%")
# 3 differing objects matching ‘%||%’ were found
# in the following places
#   namespace:ggplot2
#   namespace:gtable
#   namespace:plyr
#   namespace:reshape2
#   namespace:scales
# Use [] to view one of them

Edit: note that [] accepts numeric arguments, not the package names

Matt Bannert
  • 27,631
  • 38
  • 141
  • 207
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485