Let's say I have a function, which takes three logical arguments and returns a string indicating which of those were set to TRUE:
func_log <- function(option_1, option_2, option_3) {
if (option_1 && option_2 && option_3) {
opt <- "all"
} else {
if (option_1 && option_2) {
opt <- "first two"
} else {
if (option_1 && option_3) {
opt <- "first, last"
} else {
opt <- "last two"
}
}
}
return(opt)
}
Is there a way to avoid constructing these if-else here? Using switch
may be (would be grateful for an example then)? Any other way?
How about
myfun <- function(...) which(c(...))
# examples
myfun(TRUE,FALSE,TRUE)
# [1] 1 3
myfun(FALSE,FALSE,TRUE,TRUE,FALSE,TRUE)
# [1] 3 4 6
You could put names on these cases if you wanted to, like
mystrfun <- function(...) toString(c(letters,LETTERS)[myfun(...)])
mystrfun(TRUE,FALSE,TRUE)
# [1] "a, c"
mystrfun(FALSE,FALSE,TRUE,TRUE,FALSE,TRUE)
# [1] "c, d, f"
Replace c(letters,LETTERS)
with whatever your desired names are, and they'll get strung together.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments