lundi 31 juillet 2017

Multiple ifelse statements in R - Conditionally create new variable

I'm having a little issue. Relatively new to R.

What I am trying to do is to create a new variable (data$V4) based on the value of an existing variable (data$V3).

The condition is that if the value in variable 3 is within a certain range (e.g., >=0 & <=100), then the value in data$V4 = 1. There need to be 20 statements exactly of this sort.

I have created a code which works only for two expressions, it does not go beyond this for some reason. I don't seem to be closing the statement.

data$V4 <- ifelse((data$V3>=0) & (data$V3<=100), 1, ifelse((data$V3>=101) & (data$V3<=400), 2,0)

This code works fine. But adding more expressions with the code below fails.

data$V4 <- ifelse((data$V3>=0) & (data$V3<=100), 1,
              ifelse((data$V3>=101) & (data$V3<=400), 2,
                     ifelse((data$V3>=401) & (data$V3<=800), 3,
                            ifelse((data$V3>=801) & (data$V3<=1200), 4,0))

Aucun commentaire:

Enregistrer un commentaire