0 votes
1 view
in R Programming by (7.3k points)

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 (25.4k points)

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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...