vendredi 30 octobre 2020

Why R only excute my last if statement in for loop

I am new to R and I am trying to do for loop in R with if/else if statment The score data looks like this[Score data]Score data2

I want to create a new variable called Student2_Score where if only 1 score is missing than the Student2_Score = 0.5average of assignment1,2,3 +0.5average of assignment and the missing score is ignored and if more than 1 score is missing than the Student2_Score = NA

  Score$NA_count <- apply(Score, 1, function(x) sum(is.na(x[2:6])))
for (i in nrow(Score)) {
  if(Score$NA_count[i] > 1){Score$Student2_Score<-"NA"}
  else if (Score$NA_count[i] == 1 && is.na(Score$"1c"[i]) == T)
          {Score$Student2_Score<-((Score$"2c"+Score$"3c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if (Score$NA_count[i] == 1 && is.na(Score$"2c"[i]) == T)
    {Score$Student2_Score<-((Score$"1c"+Score$"3c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if (Score$NA_count[i] == 1 && is.na(Score$"3c"[i])== T)
    {Score$Student2_Score<-((Score$"1c"+Score$"2c")/2)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
  else if  (Score$NA_count[i] == 0) 
    {Score$Student2_Score<-((Score$"2c"+Score$"1c"+Score$"3c")/3)*0.5+((Score$"4c"+Score$"5c")/2)*0.5}
}

But the Student2_Score I got for only 1 missing score is still NA, since like R only excute the last else if statement. I would appreciate any idea and help! Thanks:)

Aucun commentaire:

Enregistrer un commentaire