2013-06-20 61 views
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 
+2

你應該把語言放在標籤中。它在標題中沒有地位。 – christopher

回答

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' 
相關問題