2015-10-06 104 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