12

I am working with weatherAUS dataset that is avaiable in the R libraries. I am trying to replace "Yes" to 1 and "No" to 0 in the RainTomorrow column.

I wrote this but it doesn't seem to work:

weather4$RainTomorrow[weather4$RainTomorrow=="Yes"]<-1 

I just says:

Warning message: In [<-.factor(*tmp*, weather4$RainTomorrow == "Yes", value = c(NA, : invalid factor level, NA generated

What does it mean and what should I do? I reckon I should use as.numeric or as.factor somewhere but I don't know how really.

3
  • Just do as.integer(as.character(weather$RainTomorrow)=="Yes")
    – akrun
    May 15, 2017 at 18:08
  • No, just keep it as it is. Why do you believe 0/1 is needed instead of a factor variable?
    – Roland
    May 15, 2017 at 18:18
  • Hi guys. See my post below. I just solved the problem. May 15, 2017 at 18:21

3 Answers 3

16

You can easily do this with dplyr.

require(dplyr)
weather4 <- weather4 %>%
      mutate(RainToday = ifelse(RainToday == "No",0,1))

Hope this helps

6
library(data.table)   
weather4[,":="(RainTomorrow=ifelse(RainTomorrow=="no",0,1))]

or simply use:

as.numeric(as.factor(weather4$RainTomorrow))
2
  • Don't use ifelse in data.table. It's inefficient. Use a join or simple subsetting. However, I don't see why data.table is needed if OP isn't already using it.
    – Roland
    May 16, 2017 at 5:23
  • 1
    @Roland how about as.numeric(as.factor(weather4$RainTomorrow)), I test it on my side, it is more efficient compare with ifelse.
    – BENY
    May 16, 2017 at 13:57
3

This is a fairly common thing when one is testing different models. For instance, decision trees work well with "Yes" and "No". However some Regression models demands 1 and 0. Particular Logistic Regression.

I solved this by using the plyr library. It was extremely easy and convenient. Here is my solution.

Origin of solution is here.

library(plyr)
weather5$RainToday <- revalue(weather5$RainToday, c("Yes"=1))
weather5$RainToday <- revalue(weather5$RainToday, c("No"=0))
head(weather5$RainToday)
[1] 0 1 1 1 1 0
Levels: 0 1

Peace!

3
  • 1
    "However some Regression models demands 1 and 0" - generally, for most base R statistical procedures you don't need such conversion - your variable is factor so it will be handled properly. You can try it by yourself: glm(RainToday ~ ., data = weather5, family = binomial) May 15, 2017 at 18:58
  • Thanks. I did not know that. I think my variable wasn't factor before which forced me to convert them into 1 and 0. May 15, 2017 at 20:04
  • Don't think my variable is factor. Error in eval(expr, envir, enclos) : y values must be 0 <= y <= 1 May 15, 2017 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.