Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in R, "Yes" to 1 and "No" to 0

Tags:

r

dataset

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.

like image 400
sockevalley Avatar asked May 15 '17 18:05

sockevalley


People also ask

How do I replace values with 0 in R?

Replace NA values with 0 using is.na() If it is NA, it will return TRUE , otherwise FALSE . So by specifying it inside-[] (index), it will return NA and assigns it to 0. In this way, we can replace NA values with Zero(0) in an R DataFrame. In the above output, we can see that NA values are replaced with 0's.

How do I replace specific values in R?

To replace a column value in R use square bracket notation df[] , By using this you can update values on a single column or on all columns. To refer to a single column use df$column_name .

Is there a Replace function in R?

Replacing values in a data frame is a very handy option available in R for data analysis. Using replace() in R, you can switch NA, 0, and negative values with appropriate to clear up large datasets for analysis.

How do I replace specific values with NA in R?

Using R replace() function to update 0 with NA R has a built-in function called replace() that replaces values in a vector with another value, for example, zeros with NAs.


1 Answers

You can easily do this with dplyr.

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

Hope this helps

like image 81
Nico Coallier Avatar answered Nov 13 '22 17:11

Nico Coallier