作者:i92202502907823 | 来源:互联网 | 2022-12-06 13:34
1> r2evans..:
来自help("$")
:
'x$name' is equivalent to 'x[["name", exact = FALSE]]'
当您向后滚动并阅读时exact=
:
exact: Controls possible partial matching of '[[' when extracting by
a character vector (for most objects, but see under
'Environments'). The default is no partial matching. Value
'NA' allows partial matching but issues a warning when it
occurs. Value 'FALSE' allows partial matching without any
warning.
因此,这为您提供的部分匹配能力都 $
和[[
索引:
mtcars$cy
# [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
mtcars[["cy"]]
# NULL
mtcars[["cy", exact=FALSE]]
# [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
我无法看到禁用exact=FALSE
默认值$
(除非您想要混淆formals
,我不建议为了重现性和一致行为).
编程使用框架和列表(用于防御目的)应该更喜欢[[
过$
的正是这个道理.(这种情况很少见,但我被这种宽容的行为所困扰.)
编辑:
为清楚起见,最后一点:
mtcars$cyl
变 mtcars[["cyl"]]
mtcars$cyl[1:3]
变 mtcars[["cyl"]][1:3]
mtcars[,"cy"]
不是问题,也不是问题 mtcars[1:3,"cy"]
一个环形解决方案可能是设置`warnPartialMatchDollar`选项然后设置R以将警告提升为错误.但不是很理想.
(预先:该选项很容易破坏重复性.)设置`options(warnPartialMatchDollar = FALSE)`与设置`options(stringsAsFactors = FALSE)`有同样的注意事项:只要*your*script(或*你的*`〜/ .Rprofile`)已加载,但您的代码依赖于此行为但在不同的环境中运行将不会表现相同,并且没有明显的迹象表明这将发生.如果使用此选项,*在每个脚本*(使用`$`索引)中使用它.或者使用`[[`.