为什么table函数会找到已删除的变量

时间:2013-06-20 15:53:05

标签: r r-table

为什么表函数会找到已删除的变量?

Dog <- c("Rover", "Spot")
Cat <- c("Scratch", "Fluffy")

Pets <- data.frame(Dog, Cat)  #create a data frame with two variables
names(Pets)
# [1] "Dog" "Cat"

#rename Dog to a longer name

names(Pets)[names(Pets)=="Dog"] <- "Dog_as_very_long_name"
Pets$Dog <- NULL # delete Dog  
names(Pets) 
#[1] "Dog_as_very_long_name" "Cat"  #the variable dog is not in the data set anymore

table(Pets$Dog)  #Why does the table function on a variable that was deleted


#  Rover  Spot 
#  1     1 

1 个答案:

答案 0 :(得分:11)

这仅仅是因为在$的某些用途中发生的部分匹配。

试试这个:

> table(Pets$Ca)

 Fluffy Scratch 
      1       1 

使用[[表示法将为您提供更多控制权。

> table(Pets[["Ca"]])
< table of extent 0 >
> table(Pets[["Ca", exact = FALSE]])

 Fluffy Scratch 
      1       1 

您可以使用options设置在使用部分匹配时发出警告。考虑:

> options(warnPartialMatchDollar = TRUE)
> table(Pets$Ca)

 Fluffy Scratch 
      1       1 
Warning message:
In Pets$Ca : partial match of 'Ca' to 'Cat'
> table(Pets$Dog)

Rover  Spot 
    1     1 
Warning message:
In Pets$Dog : partial match of 'Dog' to 'Dog_as_very_long_name'