是否有办法禁用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

最新更新