Last active
August 29, 2015 14:09
-
-
Save datalove/a002fb6b8375fc5af955 to your computer and use it in GitHub Desktop.
SQL-like decode statement for R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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