Created
June 6, 2012 14:28
-
-
Save HarlanH/2882227 to your computer and use it in GitHub Desktop.
vswitch
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
vswitch <- function(namedList, default=NA, selector) { | |
# Function adapted from Bill Dunlap that implements something along the lines of a vectorized switch statement. | |
# http://tolstoy.newcastle.edu.au/R/e8/devel/09/12/1122.html | |
# | |
# Args: | |
# namedList - e.g., list(times=df$a * df$b, plus=df$a + df$b) | |
# default - a value to assign to elements of selector that aren't matched in namedList | |
# selector - e.g., c('times', 'times', 'plus', 'exp', 'plus') | |
# | |
# Returns: a vector of values selected from namedList | |
# | |
# Example: | |
# df <- data.frame(a=c(1,2,3,4,5), b=c(10, 9, 8, 7, 6)) | |
# vswitch(namedList = list(times=df$a * df$b, plus=df$a + df$b), | |
# default = NA, | |
# selector = c('times', 'times', 'plus', 'exp', 'plus')) | |
# yields: 10 18 11 NA 11 | |
# | |
###################### | |
result <- rep(default, length.out=length(namedList[[1]])) | |
for (sel in intersect(unique(selector[!is.na(selector)]), names(namedList))) { | |
i <- sel == selector | |
i[is.na(i)] <- FALSE | |
result[i] <- namedList[[sel]][i] | |
} | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment