r – Warning message: In `…` : invalid factor level, NA generated

r – Warning message: In `…` : invalid factor level, NA generated

The warning message is because your Type variable was made a factor and lunch was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force Type to be a character.

> 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

If you are reading directly from CSV file then do like this.

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

r – Warning message: In `…` : invalid factor level, NA generated

Here is a flexible approach, it can be used in all cases, in particular:

  1. to affect only one column, or
  2. the dataframe has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).

First, un-factorize a string using the as.character function, and, then, re-factorize with the as.factor (or simply factor) function:

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)

Leave a Reply

Your email address will not be published.