微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决有没有办法在列表索引中禁用 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。