jeudi 2 juin 2016

Multiple actions from multiple if / else if statements - R

I'm new to R and am experiencing a problem properly populating a column of data within a data frame. I'm populating two columns (P_Score and P_Class) based on another column (P_Value) using a series of if / else if statements.

i<- 0
nr<- nrow(myData)
while(i<nr){
  i<-1+i
  if(toString(myData$P_Value[i])=="NA"){ myData$P_Score[i] <- myData$P_Value[i]
  } else if (as.numeric(toString(myData$P_Value[i]))<5){
      myData$P_Score[i] <- 1; myData$P_Class[i] <- "Minimal Depression";
  } else if (as.numeric(toString(myData$P_Value[i]))<10){
      myData$P_Score[i] <- 2; myData$P_Class[i] <- "Mild Depression";
  } else if (as.numeric(toString(myData$P_Value[i]))<15){
      myData$P_Score[i] <- 3; myData$P_Class[i] <- "Moderate Depression";
  } else if (as.numeric(toString(myData$P_Value[i]))<20){
      myData$P_Score[i] <- 4; myData$P_Class[i] <- "Moderate-Severe Depression";
  } else 
      myData$P_Score[i] <- 5; myData$P_Class[i] <- "Severe Depression";
}

However, this is not giving me my desired result, and instead I wind up with this:

P_Value  P_Score    P_Class
4        1          Severe Depression
25       5          Severe Depression
8        2          Severe Depression
13       3          Severe Depression
17       4          Severe Depression
1        1          Severe Depression
12       3          Severe Depression

So the P_Score is populating just fine, but the P_Class is always defaulting to "Severe Depression". I must be having some issue executing multiple statements based off of 1 if condition, but I can't figure out what I'm doing wrong. I have read elsewhere as long as you put semicolons after the statements both should work, but that's clearly not working.

I have also tried spacing out the commands like this:

} else if (as.numeric(toString(myData$P_Value[i]))<5){
  myData$P_Score[i] <- 1
  myData$P_Class[i] <- "Minimal Depression"

But that does not seem to work either. Please help!

Aucun commentaire:

Enregistrer un commentaire