samedi 16 novembre 2019

Getting a error when using If / Else if on string in R

I am trying to convert the string characters for months into numerical representations. As you can see from the code I am attempting to convert the numbers into characters so that I am not placing a number where a character string used to be. But I am still getting the error below. I am using na.omit so there should be no NA's in the dataset.

Warning message:
In `[<-.factor`(`*tmp*`, i, value = c(8L, 11L, 11L, 8L, 8L, 2L,  :
invalid factor level, NA generated

Here is the code:

forestfires <- read.csv('forestfires.csv')

forestfireDf <- data.frame(cbind(forestfires))

forestfireDf <- na.omit(forestfireDf)

for (i in length(forestfireDf)) {
  if (forestfireDf$month[i] == 'jan') {
    forestfireDf$month[i] = as.character(1)
       } else if (forestfireDf$month[i] == 'feb') {
    forestfireDf$month[i] = as.character(2)
       } else if (forestfireDf$month[i] == 'mar') {
    forestfireDf$month[i] = as.character(3)
       } else if (forestfireDf$month[i] == 'apr') {
    forestfireDf$month[i] = as.character(4)
       } else if (forestfireDf$month[i] == 'may') {
    forestfireDf$month[i] = as.character(5)
       } else if (forestfireDf$month[i] == 'jun') {
    forestfireDf$month[i] = as.character(6)
       } else if (forestfireDf$month[i] == 'jul') {
    forestfireDf$month[i] = as.character(7)
       } else if (forestfireDf$month[i] == 'aug') {
    forestfireDf$month[i] = as.character(8)
       } else if (forestfireDf$month[i] == 'sep') {
    forestfireDf$month[i] = as.character(9)
       } else if (forestfireDf$month[i] == 'oct') {
    forestfireDf$month[i] = as.character(10)
       } else if (forestfireDf$month[i] == 'nov') {
    forestfireDf$month[i] = as.character(11)
       } else if (forestfireDf$month[i] == 'dec') {
    forestfireDf$month[i] = as.character(12)}
}

Aucun commentaire:

Enregistrer un commentaire