2011-05-19 82 views
4

我是R新手,正在嘗試以下代碼。令我驚訝的是,分配ret$log.id的東西實際上也會導致相同的值被分配到ret$log。例如,將值賦值給名稱中帶有「點」的變量

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

運行以下將返回"a"

ret$log 

這是什麼原因[R該怎麼辦?我希望有人能夠給我一些見解。

感謝,

+0

這很奇怪。如果你運行'str(ret)'或'names(ret)',結果如我所期望的那樣 - 一個名爲「log.id」的列表。有趣的是,'ret $ l'也返回「a」,但是'ret $ z'返回NULL。我想知道'$'操作符是否可以進行某種最佳猜測匹配? – Chase 2011-05-19 23:02:18

+0

部分匹配,它不分配給ret $ log - 使用名稱(ret)來查看真正存在的內容(部分匹配是R的一個分支) – mdsumner 2011-05-19 23:29:43

+4

另請參閱'options(warnPartialMatchDollar = T)'如果你想跟蹤這些。 – Charles 2011-05-20 00:31:57

回答

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 

我認爲大通是正確的 - 在遊戲中部分匹配。

有趣的是,如果有匹配部分匹配的是兩列,則返回NULL,而不是一個警告:

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

> y$sa 
NULL 
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 
6

闡述一下部分匹配大錯。從幫助頁面$

下參數:

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. 

然後根據性格指標:

​​

此外,根據字符索引:

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). 

還有更多的細節如names和中所提及的但是這爲我清除了它。