dimanche 15 juillet 2018

New variable using for, if and else if functions

I have created a data frame with test scores for three different tests. I would now like to create a new variable in the same data frame ('highest_score') stating which of three scores was the individual's highest. I have created the following code to do this:

test <- data.frame(test_1, test_2, test_3) 
# this gives me a dataframe with scores from three different tests (6 observations in each) 

Then,

for (i in 1:nrow(test)) {
  if ((test$test_1[i] > test$test_2[i]) & (test$test_1[i] > test$test_3[i]))
      test$highest_score <- "Test 1 is the individual's highest score!"
} else if ((test$test_2[i] > test$test_1[i]) & (test$test_2[i] > 
test$test_3[i]))
       test$highest_score <- "Test 2 is the individual's highest score!"
} else if ((test$test_3[i] > test$test_1[i]) & (test$test_3[i] > 
test$test_2[i]))
       test$highest_score <- "Test 3 is the individual's highest score!"
} else 
  NULL
}
}

When I run the code, the new variable 'highest_score' prints out the 'Test 3 is the individual's highest score!' for all observations, even though that is not true.

I would be very grateful if someone was able to let me know where I am going wrong.

Aucun commentaire:

Enregistrer un commentaire