fixed[1, ] <- c("">

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

 why getting this warning message “invalid factor level, na generated”.

 

> 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     100
2           0
3           0

The warning message appeared because, in R, character values are by default treated as factors while a data frame is created. Thus, while creating your data frame, the variable “Type” was made a factor, and “lunch” was not a predefined level in that factor.i.e.,

fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame': 3 obs. of 2 variables:
 $ Type : Factor w/ 1 level "": 1 1 1
 $ Amount: num 0 0 0

To avoid this warning, you can include the argument stringsAsFactors = FALSE to force R not to convert ‘Type’ to a factor while creating the data frame.i.e.,

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"

Your Answer

Interviews

Parent Categories