6

为什么表函数会找到一个被删除的变量?

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 
4

1 回答 1

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'
于 2013-06-20T16:08:51.833 回答