R: If 语句包含 is.null 作为 OR 连接的条件之一
R: If statement contains is.null as one of the conditions connected by OR
我有一个变量mat
,它的初始值为NULL
。我有一个迭代过程,只会在特定条件下填充垫子。在此过程之后,我检查 mat
是否超过一定数量的行,如果没有,则执行其他操作。
我正在寻找一种简洁的方式来编写此条件,理想情况下,类似于 is.null(mat) | nrow(mat) < n
。虽然如果 is.null(mat)
是 TRUE
并且它们通过 OR 连接,整个语句应该是 TRUE
,但是 nrow(mat) < n
会报错。
我可以通过将其重写为两个条件并将 # do something
代码复制到两个地方来解决这个问题,但是有没有更简洁的方法来做到这一点?
mat = NULL
for(i in 1:10){
if(runif(1) > 0.8){
mat = rbind(mat, c(1,2,3))
}
}
if(is.null(mat)){
# do something...
} else if(nrow(mat) < 3){
# do something...
}
您可以使用|
的短路版本,即||
。
is.null(mat) || nrow(mat) < n
来自帮助:
& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.
我有一个变量mat
,它的初始值为NULL
。我有一个迭代过程,只会在特定条件下填充垫子。在此过程之后,我检查 mat
是否超过一定数量的行,如果没有,则执行其他操作。
我正在寻找一种简洁的方式来编写此条件,理想情况下,类似于 is.null(mat) | nrow(mat) < n
。虽然如果 is.null(mat)
是 TRUE
并且它们通过 OR 连接,整个语句应该是 TRUE
,但是 nrow(mat) < n
会报错。
我可以通过将其重写为两个条件并将 # do something
代码复制到两个地方来解决这个问题,但是有没有更简洁的方法来做到这一点?
mat = NULL
for(i in 1:10){
if(runif(1) > 0.8){
mat = rbind(mat, c(1,2,3))
}
}
if(is.null(mat)){
# do something...
} else if(nrow(mat) < 3){
# do something...
}
您可以使用|
的短路版本,即||
。
is.null(mat) || nrow(mat) < n
来自帮助:
& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.