为何R语言if语句中which()函数的输出会被抑制?
问题:为何if语句块中which()的输出被抑制?
我有一个部分单元格包含字符串"BLQ"的数据框,可通过如下代码定位这些单元格:
which(df == "BLQ", arr.ind = TRUE)
某次示例中,执行length(which(df == "BLQ", arr.ind = TRUE))得到结果为492。单独执行以下代码:
which(df == "BLQ", arr.ind = TRUE) stop("BLQ still present")
会显示所有BLQ所在的行和列,随后程序终止并输出预期信息:
Error: BLQ still present
但将上述两句代码放入如下if语句块后:
if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){ which(df == "BLQ", arr.ind = TRUE) stop("BLQ still present") }
which()函数的输出被抑制,仅显示错误信息。请问这是为什么?
解答
这是因为R中只有顶级表达式的结果才会自动打印,if语句块内部的表达式属于非顶级表达式,默认不会自动输出结果。
- 单独执行
which(df == "BLQ", arr.ind = TRUE)时,它是顶级表达式,R会自动打印其返回值; - 放到if的代码块里后,它变成了代码块中的子表达式,R不会主动打印子表达式的结果,除非你显式调用
print()函数。
如果想要在if块中看到which()的输出,修改代码为:
if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){ print(which(df == "BLQ", arr.ind = TRUE)) stop("BLQ still present") }
另外,为了避免重复执行which(df == "BLQ", arr.ind = TRUE)(两次调用会浪费计算资源),可以把结果先存到变量里:
blq_pos <- which(df == "BLQ", arr.ind = TRUE) if (length(blq_pos) != 0){ print(blq_pos) stop("BLQ still present") }
内容的提问来源于stack exchange,提问作者please help
相关产品推荐
相关产品推荐

