Alternative if-then-else with booleans in R

Let's say I have a function that takes three boolean arguments and returns a string indicating which one was 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 any way to avoid creating if-else here? The use switchcan be (would be grateful for an example then)? Any other way?

+4
source share
2 answers

What 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 can put names in these cases if you want, for example

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 with c(letters,LETTERS)any of your desired names and they will be strung together.

+4
source

Another idea ... Manually list the cases in the table, then matchor merge, to assign them:

mynames <- read.table(header=TRUE,colClasses="character",text="
case name
000  nope
001  last
011  lasttwo
010  middler
100  first
110  firsttwo
111  allyall
101  nomid")

myoddfun <- function(...) with(mynames,name[match(paste0(+c(...),collapse=""),case)])

myoddfun(TRUE,FALSE,TRUE)
# [1] "nomid"
myoddfun(FALSE,FALSE,FALSE)
# [1] "nope"
+2
source

Source: https://habr.com/ru/post/1599585/


All Articles