Skip to content

Instantly share code, notes, and snippets.

@casallas
Last active August 29, 2015 14:13
Show Gist options
  • Save casallas/8fca5ab50a92193151a4 to your computer and use it in GitHub Desktop.
Save casallas/8fca5ab50a92193151a4 to your computer and use it in GitHub Desktop.
||++ for R
# return a if a is defined and not null, otherwise return b
`%|%` <- function(a, b){
try({
if(!is.null(eval(substitute(a))))
return(a)
}, silent=TRUE);
b
}
# assign b to a if a is undefined or null, compare to ruby's ||=
`%<|-%` <- function(a, b){
# This should generate a <- a %|% b, see http://rpubs.com/hadley/do-call2
# Use `<-` instead of assign to allow things like df$a %<|-% 2
do.call(`<-`,
list(substitute(a), substitute(a %|% b)),
envir=parent.frame())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment