将值分配给名称中带有“点”的变量

时间:2011-05-19 22:52:28

标签: r

我是R的新手,正在尝试以下代码。令我惊讶的是,为ret$log.id分配内容实际上会导致将相同的值分配给ret$log。如,

 ret <- c()
 ret$log.id <- 'a'

运行以下内容将返回"a"

ret$log

这是R应该做的吗?我希望有人可以给我一些洞察力。

谢谢,

3 个答案:

答案 0 :(得分:6)

是的,$运营商正在做一些部分匹配。您可以使用以下内容稍微探索一下该行为:

ret <- c()
ret$log.id <- "a"

ret$l #Returns "a"

ret$log.at <- "b"

现在看看返回的内容如下:

ret$l
ret$log
ret$log.i
ret$log.a

答案 1 :(得分:6)

详细说明部分匹配的boner。在$的帮助页面中:

根据参数:

name     A literal character string or a name (possibly backtick quoted).
For extraction, this is normally (see under ‘Environments’) partially matched to the names 
of the object.

然后在字符索引下:

Character indices can in some circumstances be partially matched (see pmatch) to the 
names or dimnames of the object being subsetted (but never for subassignment). 

同样在字符索引下:

Thus 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(warnPartialMatchAttr = TRUE).

namespmatch中提到了更多详细信息,但我已将其清除。

答案 2 :(得分:4)

这是正常行为:

x = data.frame(happy = rnorm(10), sad = rnorm(10))

> x$hap
 [1] -0.9373243 -0.9497992 -0.1413024 -0.9857493  1.7156495  0.8715162  0.8377111
 [8] -0.4161816 -0.3976979 -0.2569765

我觉得Chase是对的 - 在游戏中部分匹配。

有趣的是,如果有两列匹配部分匹配,则返回NULL而不是警告:

y = data.frame(happy = rnorm(10), sad = rnorm(10), sadder = rnorm(10))

> y$sa
NULL