# Assigning grades to a vector based on multiple conditions

I have two vectors

vThresholds = as.vector(c(0.12, 0.34, 0.56, 0.85)) vCandidates = as.vector(rnorm(100))

I want to assign grades to the candidates based on where they lie in vThresholds. I wrote a function as follows

fGrades = function (x, y) { if(y <= x[1]){ grade = "A" } else if(y > x[1] & y <= x[2]){ grade = "B" } else if(y > x[2] & y <= x[3]){ grade = "C" } else if(y > x[3] & y <= x[4]){ grade = "D" }else {grade = "E"} grade }

However, when I use

mapply(fGrades, vThresholds, vCandidates)

I get an error

Error in if (y <= x[1]) { : missing value where TRUE/FALSE needed

On tracing this error I find that mapply coverts x into NA.

I can get around this problem by looping through vCandidates. However, I am looking for a vectorized version of this solution. Is there an easier way to do this?

## Answers

Maybe something more like this...?

LETTERS[1:5][findInterval(vCandidates,vThresholds)+1]

Side note: the as.vector isn't necessary.

Be sure to read ?findInterval carefully to make sure you're getting the behavior that you want on the boundaries of the intervals.

A short explanation of the error you got:

It's not so much that mapply is converting anything, but that you asked for an element of x that doesn't exist. mapply sends only a single value to the function fGrades for each of x and y. So when inside that function you ask for x[2], R returns NA, since in that context x has length of only 1.