[R] assign if not set

Marc Schwartz marc_schwartz at comcast.net
Tue Nov 20 02:03:47 CET 2007


On Tue, 2007-11-20 at 03:32 +0300, Alexy Khrabrov wrote:
> What's the idiom of assigning a default value to a variable if it's  
> not set?  In Ruby one can say
> 
> v ||= default
> 
> -- that's an or-assign, which triggers the assignment only if v is  
> not set already.  Is there an R shorthand?
> 
> Cheers,
> Alexy

If 'v' is not set, then it does not exist, hence you can use exists() to
check for it. However, you need to [potentially] distinguish where the
variable might be located. Keep in mind that R uses lexical scoping,
hence the exists() function has other arguments to define where to look.

A simple example:

> v
Error: object "v" not found

if (!exists("v")) v <- "Not Set"

> v
[1] "Not Set"

v <- "Set"

if (!exists("v")) v <- "Not Set"

> v
[1] "Set"


See ?exists for more information.

That being said, just as an example of extending R, you could do the
following, which is to create a new function %||=% (think %in% or %*%)
which can then take two arguments, one preceding it and one following
it, and then basically do the same thing as above. Again here, scoping
is critical.


"%||=%" <- function(x, y) 
{
  Var <- deparse(substitute(x))
  if (!exists(Var)) 
    assign(Var, y, parent.frame())
}

> v
Error: object "v" not found

v %||=% "Not Set"

> v
[1] "Not Set"

v <- "Set"

v %||=% "Not Set"

> v
[1] "Set"


HTH,

Marc Schwartz



More information about the R-help mailing list