Skip to content

Instantly share code, notes, and snippets.

@HarlanH
Created June 6, 2012 14:28
Show Gist options
  • Save HarlanH/2882227 to your computer and use it in GitHub Desktop.
Save HarlanH/2882227 to your computer and use it in GitHub Desktop.
vswitch
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