为什么R找到不在data.frame中的data.frame变量?

时间:2013-03-05 05:20:10

标签: r

为什么这不会导致错误?

> str(u)
'data.frame':   8879 obs. of  2 variables:
 $ bundle_qty: int  1 1 1 1 1 1 1 1 1 1 ...
 $ mail_a    : num  1 1 1 1 0 0 0 1 1 0 ...

> head(u$mail)
[1] 1 1 1 1 0 0

变量mail不在data.frame u中!不应该u$mail返回NULL ??

即使我从头开始使用虚拟数据:

> rm(list=ls())
> u <- data.frame( bundle_qty = c(1,1,1,1), mail_a = c(1,1,1,1))
> str(u)
'data.frame':   4 obs. of  2 variables:
 $ bundle_qty: num  1 1 1 1
 $ mail_a    : num  1 1 1 1
> u <- data.frame( bundle_qty = c(1L,1L,1L,1L), mail_a = c(1,1,1,1))
> str(u)
'data.frame':   4 obs. of  2 variables:
 $ bundle_qty: int  1 1 1 1
 $ mail_a    : num  1 1 1 1
> u$mail
[1] 1 1 1 1

2 个答案:

答案 0 :(得分:8)

$运算符使用的部分匹配将返回一个值,如果它可以唯一地标识给定词干的变量(例如 - mail)。

E.g。 - 您的mail中没有其他内容以data.frame开头,因此您返回mail_a

u["mail"]会抛出错误。

进一步举例说明它的工作原理如你所愿:

test <- data.frame(aa=1:10,aaa=letters[1:10])

> test$aa
 [1]  1  2  3  4  5  6  7  8  9 10
> test$aaa
 [1] a b c d e f g h i j
Levels: a b c d e f g h i j
> test$a
NULL

@mnel引用的fortune(312)是:

  

“这里的问题是$符号是一个神奇的捷径,就像   任何其他魔法如果使用不正确可能会编程   相当于把自己变成了蟾蜍。“

     
      
  • Greg Snow(响应想要访问其列的用户的用户)   name通过x $ y而不是x [[y]]存储在y中   R-help(2012年2月)
  •   

答案 1 :(得分:8)

u$mail

调用相当于

u[['mail', exact = FALSE]]

它将使用部分匹配来查找命名元素(列)

u[['mail']]

不会使用部分匹配,因此不会找到任何列。

如财富(312)

中所述,使用[[更安全
 /\_/\
( o o )
== Y ==
 - -