Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (7.3k points)
edited by

I don't understand why I got this warning message.

> 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

1 Answer

0 votes
by
edited by

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"

If you wish to Learn R Programming visit this R Programming Course by Intellipaat.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...