除了部分匹配之外,$ 运算符可以做任何 [ 和 [[ 做不到的事情吗?
Aside from partial matching, can the $ operator do anything that [ and [[ cannot?
我相信 $
运算符的以下内容是正确的:
- 它允许名称部分匹配。例如,如果没有使用
Sky
名称,data$Sky
可以匹配 data$Skywalker
。
- 它不能用于原子向量,不像
[
和 [[
。
- 不能与
-
等运算符组合。没有像 mtcars$-mpg
这样的有效语法。 [
和 [[
也不能对名称执行此操作,但 mtcars[,-1]
可以。
- 仅供命名。
- 撇开部分匹配不谈,对于数据框,
data$name
等同于 data[,"name"]
例如mtcars$cyl
与 mtcars[,"cyl"]
相同。我很确定 data[["name"]]
也是等价的,例如mtcars[["cyl"]]
.
- 撇开部分匹配不谈,对于不是数据框的命名列表,
data$name
与 data[["name"]]
相同。
这是否意味着如果我不关心部分匹配,我总是可以将 $
替换为 [
或 [[
?还是我错过了一些功能?
根据一本关于高级 R 的书,除了部分匹配之外,$ 和 [ 运算符在数据帧(而不是列表)上是相同的。它指出
$ is a shorthand operator: x$y is roughly equivalent to x[["y"]].
...The one important difference between $ and [[ is that $ does
(left-to-right) partial matching:
引用如下:下一个 link 的第 4.3.2 节:
https://adv-r.hadley.nz/subsetting.html#section-1
对于 base R,我最好的猜测来自 the documentation for $。以下引述是最相关的:
$ is only valid for recursive objects
$ does not allow computed indices, whereas [[ does. x$name
is equivalent to x[["name", exact = FALSE]]
. Also, the partial matching behavior of [[
can be controlled using the exact argument.
the default behaviour is to use partial matching only when extracting from recursive objects (except environments) by $. Even in that case, warnings can be switched on by options(warnPartialMatchDollar = TRUE).
所以文档似乎证实了我的信念,即除了部分匹配之外,$
只是语法糖。但是,有四点我不确定:
- 我从不过于相信 R 的文档。因此,我相信有经验的用户一定能找出我所说的漏洞。
- 我说这只是我对基数 R 的猜测,因为
$
是一个通用运算符,因此可以通过包更改其含义,tibbles 是一个常见的例子。
$
和[
也可以用于环境,但我没见过有人这样做。
- 我不知道“计算索引”是什么。
我相信 $
运算符的以下内容是正确的:
- 它允许名称部分匹配。例如,如果没有使用
Sky
名称,data$Sky
可以匹配data$Skywalker
。 - 它不能用于原子向量,不像
[
和[[
。 - 不能与
-
等运算符组合。没有像mtcars$-mpg
这样的有效语法。[
和[[
也不能对名称执行此操作,但mtcars[,-1]
可以。 - 仅供命名。
- 撇开部分匹配不谈,对于数据框,
data$name
等同于data[,"name"]
例如mtcars$cyl
与mtcars[,"cyl"]
相同。我很确定data[["name"]]
也是等价的,例如mtcars[["cyl"]]
. - 撇开部分匹配不谈,对于不是数据框的命名列表,
data$name
与data[["name"]]
相同。
这是否意味着如果我不关心部分匹配,我总是可以将 $
替换为 [
或 [[
?还是我错过了一些功能?
根据一本关于高级 R 的书,除了部分匹配之外,$ 和 [ 运算符在数据帧(而不是列表)上是相同的。它指出
$ is a shorthand operator: x$y is roughly equivalent to x[["y"]]. ...The one important difference between $ and [[ is that $ does (left-to-right) partial matching:
引用如下:下一个 link 的第 4.3.2 节: https://adv-r.hadley.nz/subsetting.html#section-1
对于 base R,我最好的猜测来自 the documentation for $。以下引述是最相关的:
$ is only valid for recursive objects
$ does not allow computed indices, whereas [[ does.
x$name
is equivalent tox[["name", exact = FALSE]]
. Also, the partial matching behavior of[[
can be controlled using the exact argument.
the default behaviour is to use partial matching only when extracting from recursive objects (except environments) by $. Even in that case, warnings can be switched on by options(warnPartialMatchDollar = TRUE).
所以文档似乎证实了我的信念,即除了部分匹配之外,$
只是语法糖。但是,有四点我不确定:
- 我从不过于相信 R 的文档。因此,我相信有经验的用户一定能找出我所说的漏洞。
- 我说这只是我对基数 R 的猜测,因为
$
是一个通用运算符,因此可以通过包更改其含义,tibbles 是一个常见的例子。 $
和[
也可以用于环境,但我没见过有人这样做。- 我不知道“计算索引”是什么。