有没有办法在列表索引中禁用 R 缩写?

问题描述

此刻我被这段代码惊呆了:

bad.list <- list(xx = "A")
print(is.null(bad.list$x))   # FALSE: Bad since there is no x
print(is.null(bad.list$xx))  # FALSE: Correct since there is xx
print(is.null(bad.list$xxx)) # TRUE:  Correct since there is no xxx

通常您希望 is.null(bad.list$x) 被评估为 TRUE,因为列表中没有 x。但由于 R 允许您使用缩写,因此它的计算结果为 FALSE。在我的情况下,我无法更改列表条目的名称

有没有办法强制 R 禁用缩写?

解决方法

您可以使用 [[...]] 表示法:

bad.list <- list(xx = "A")
print(is.null(bad.list[["x"]]))   # is TRUE now
print(is.null(bad.list[["xx"]]))  # FALSE: Correct since there is xx
print(is.null(bad.list[["xxx"]])) # TRUE:  Correct since there is no xxx