mercredi 6 juin 2018

Ifelse statement usage in R

I have a data frame "var" and I need to get a vector output that satisfies the following conditions.

Basically, what I am trying to execute is the following: if the value of psqi_2_sleepstart1 is less than 15, comp21score needs to be assigned the value 0; between 16 and 30, comp21score needs to be assigned the value 1; between 31 and 60, comp21score needs to be assigned the value 2 and over 60 comp21score should take the value of 3. For example, if the data frame had values for psqi_2_sleepstart1 as 16, 40, 6 and 10; I want the output to be 1, 2, 0, 1. I was using the ifelse statement, but I got the error that argument "yes" is missing, with no default.

Here is my attempt:

for (i in 1: nrow(var)) {
ifelse (psqi_2_sleepstart1 <= 15) 
comp21score [i] <- 0
ifelse (psqi_2_sleepstart1 > 15 & psqi_2_sleepstart1 <= 30)
comp21score [i] <- 1
ifelse (psqi_2_sleepstart1 > 30 & psqi_2_sleepstart1 <= 60)
comp21score [i] <- 2
ifelse (psqi_2_sleepstart1 > 60)
comp21score [i] <- 3 
}
print (comp21score)

Does anyone have suggestions on what I might be able to use instead or how to avoid this error?

Thanks!

Aucun commentaire:

Enregistrer un commentaire