2015-10-06 136 views
0

數據幀'vpsots'有一個變量'type',有13個級別(下面給出),同時探索它的數據幀,試圖用SUV試圖保留SUV(只是爲了看看我能)。我應該在下面的代碼中對警告做些什麼。我看到SUV被改爲NA。我認爲這與變量'type'是一個因素有關。是否因爲「suv」級別不存在?我正努力在閱讀警告標誌方面做得更好,並希望提出建議。需要幫助解碼警告

> unique(vposts$type) 
[1] coupe  SUV   sedan  hatchback wagon  van   <NA>  
[8] convertible pickup  truck  mini-van other  bus   offroad  
13 Levels: bus convertible coupe hatchback mini-van offroad other pickup sedan SUV ... wagon 
> vposts$type[vposts$type=="SUV"]="suv" 
Warning message: 
In `[<-.factor`(`*tmp*`, vposts$type == "SUV", value = c(3L, NA, : 
    invalid factor level, NA generated 
> unique(vposts$type) 
[1] coupe  <NA>  sedan  hatchback wagon  van   convertible 
[8] pickup  truck  mini-van other  bus   offroad  
13 Levels: bus convertible coupe hatchback mini-van offroad other pickup sedan SUV ... wagon 
+2

列是'factor'。轉換爲「角色」,警告將消失。原因是這個因素沒有那個水平'suv'。您應該在替換或轉換爲字符之前添加該「級別」。 – akrun

+2

這些因素是特定於案例的。 「suv」不是其中一個因素,所以它會被強制轉換爲「NA」。 –

回答

1

爲了重命名一個因素的水平,你可以做以下使用levels功能:

# Create a factor with each alphabet letter as levels. 
a_factor <- factor(substring("statistics", 1:10, 1:10), levels = letters) 
summary(a_factor) 

a b c d e f g h i j k l m n o p q r s t u v w x y z 
1 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 3 3 0 0 0 0 0 0 

# Rename the level whose name is "c". 
levels(a_factor)[levels(a_factor) == "c"] <- "CE" 
summary(a_factor) 

a b CE d e f g h i j k l m n o p q r s t u v w x y z 
1 0 1 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 3 3 0 0 0 0 0 0