2013-05-29 7 views
95

Non capisco perché ho ricevuto questo messaggio di avviso.Messaggio di avviso: in `...`: livello di fattore non valido, NA generato

messaggio
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3)) 
> fixed[1, ] <- c("lunch", 100) 
Warning message: 
In `[<-.factor`(`*tmp*`, iseq, value = "lunch") : 
    invalid factor level, NA generated 
> fixed 
    Type Amount 
1 <NA> 100 
2   0 
3   0 

risposta

150

L'avvertimento è perché la variabile "Tipo" è stato fatto un fattore e "pranzo" non era un livello definito. Utilizzare il flag stringsAsFactors = FALSE quando si crea il frame di dati per forzare "Type" a essere un carattere.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3)) 
> str(fixed) 
'data.frame': 3 obs. of 2 variables: 
$ Type : Factor w/ 1 level "": NA 1 1 
$ Amount: chr "100" "0" "0" 
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE) 
> fixed[1, ] <- c("lunch", 100) 
> str(fixed) 
'data.frame': 3 obs. of 2 variables: 
$ Type : chr "lunch" "" "" 
$ Amount: chr "100" "0" "0" 
+1

@David Perché R lo converte in fattore? – KannarKK

+1

Perché questa è l'impostazione predefinita nella funzione 'data.frame()' (ed è predefinita perché è quella che la maggior parte degli utenti desidera la maggior parte delle volte). – David

34

Se stai leggendo direttamente dal file CSV, fai come questo.

myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE) 
9

Questo un approccio flessibilità, può essere utilizzato in tutti i casi, in particolare:

  1. si vuole solo influenzare una colonna, o
  2. il data.frame ha portato dall'applicazione delle operazioni precedenti (ad esempio non aprire immediatamente un file o creare il frame di dati).

In primo luogo, non-factorize una stringa utilizzando la funzione as.character, e, quindi, ri-factorize con la funzione as.factor (o semplicemente factor):

fixed <- data.frame("Type" = character(3), "Amount" = numeric(3)) 

# Un-factorize (as.numeric can be use for numeric values) 
#    (as.vector can be use for objects - not tested) 
fixed$Type <- as.character(fixed$Type) 
fixed[1, ] <- c("lunch", 100) 

# Re-factorize with the as.factor function or simple factor(fixed$Type) 
fixed$Type <- as.factor(fixed$Type) 
3

Il Il modo più semplice per risolvere questo problema è aggiungere un nuovo fattore alla colonna. Usa la funzione livelli per determinare quanti fattori hai e poi aggiungi un nuovo fattore.

> levels(data$Fireplace.Qu) 
    [1] "Ex" "Fa" "Gd" "Po" "TA" 
    > levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None") 
    [1] "Ex" "Fa" "Gd" "Po" " TA" "None"