mardi 23 janvier 2018

R: assign value based on criteria

I am trying to convert test scores from a psychological questionnaire in the first data set to standardized scores (range of percentiles) in another data set

The test scores are one score from 9 people that took my questionnaire

TestResults <- data.frame(ID = c(1:9),   
               Observed = c(14, 8, 33, 23, 5, 79, 2, 11, 5), Results = NA) 

The Scoring sheet, from the test publisher, implemented manually in R, shortened here for simplicity

ScoringSheet <- data.frame(Percentiles = c(99,95,85,55,10), Score = c(79,33,20,15,5))

I would like to fill the column Results, with the corresponding percentile values for the observed scores from the ScoringSheet. For the scoring, a simple algorithm applies, which I just can't get implemented in R

1 if TestResults$Observed %in% ScoringSheet$Score, then Results should be the corresponding Percentiles value in the ScoringSheet.
2 if !(TestResults$Observed %in% ScoringSheet$Score), then TestResults$Results should be the average of the two ScoringSheet$Percentiles between which the Observedscore falls
3 if TestResults$Observed < min(ScoringSheet$Score) then the Results value for these smallest observed value should be min(ScoringSheet$Percentiles)/2

As a result, I would need this

TestResults <- data.frame(ID = c(1:9), 
                           Observed = c(14, 8, 33, 23, 5, 79, 2, 11, 5), 
                           Results = c(0.5,0.5,95,90,0.5,99,0.5,0.5,0.5))

Until now, I can get the corresponding percentiles for criterion 1 using merge() on TestResults$Observed and ScoringSheet$Score, creating NAs for the values that are not exactly matching. I am now wondering how to implement criterion 2 and 3.

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire