有没有更优雅的方式在 R 中编写嵌套
if
语句?
cond1 <- T
cond2 <- F
cond3 <- T
if (cond1)
if(cond2)
if(cond3)
x <- 1
考虑到只有前一个条件为
TRUE
时才必须评估某个条件(在需要时间才能获得 cond2
、cond3
等的情况下)
我想要类似于以下代码的东西:
x <- multiple_if(1, cond1, cond2, cond3)
我知道
purrr::when
功能,但它不能满足我的需求。
也许下面的代码可以解决问题。它使用
mget
将逻辑变量放入要传递给 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
创建于 2022 年 10 月 2 日,使用 reprex v2.0.2
不要忽视基本 r 中非常有用的
all()
和 any()
函数。
x <- all(cond1, cond2, cond3) # returns TRUE if ALL conditions are TRUE
x <- any(cond1, cond2, cond3) # returns TRUE if ANY condition is TRUE