Skip to content

Instantly share code, notes, and snippets.

@datalove
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datalove/a002fb6b8375fc5af955 to your computer and use it in GitHub Desktop.
Save datalove/a002fb6b8375fc5af955 to your computer and use it in GitHub Desktop.
SQL-like decode statement for R
decode <- function(x, ...) {
odds <- function(x) { unlist(x[1:length(x) %% 2 == 1][1:floor(length(x)/2)]) }
even <- function(x) { unlist(x[1:length(x) %% 2 == 0]) }
last <- function(x) { unlist(if(length(x) %% 2 == 1) tail(x,1)) }
interpret_args <- function(x) { if(is.call(x)) {eval(x)} else if(is.name(x)) {as.character(x)} else {x} }
args <- eval(substitute(alist(...)))
args <- lapply(args, interpret_args)
targets <- odds(args)
replacements <- even(args)
default <- last(args)
res <- x
if(!is.null(default))
res[! x %in% targets & ! is.na(x)] <- default
for(i in seq_along(targets)) {
t <- targets[[i]]; r <- replacements[[i]]
res[res == t | (is.na(t) & is.na(res))] <- r
}
if(inherits(x, "factor"))
res <- as.factor(res)
res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment