Home > Mobile >  Is there an elegant way to write nested if statements in R?
Is there an elegant way to write nested if statements in R?

Time:10-02

Is there a more elegant way to write nested if statements in R?

cond1 <- T 
cond2 <- F
cond3 <- T

if (cond1)
  if(cond2)
    if(cond3)
      x <- 1

Consider that a condition must only be evaluated if the previous one is TRUE (in the case that it takes time to get cond2, cond3, etc)

I want something similar to the following code:

x <- multiple_if(1, cond1, cond2, cond3) 

I know the purrr::when function, but it does not satisfy my needs.

CodePudding user response:

Maybe the following code solves the question's problem. It uses mget to put the logical variables in a list to be passed to Reduce.

cond1 <- TRUE
cond2 <- FALSE
cond3 <- TRUE

l <- mget(ls(pattern = "^cond"))
l
#> $cond1
#> [1] TRUE
#> 
#> $cond2
#> [1] FALSE
#> 
#> $cond3
#> [1] TRUE

Reduce(`&&`, l)
#> [1] FALSE

Created on 2022-10-02 with reprex v2.0.2

  • Related