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.


Need Your Help

Sending asp.net page content to Microsoft Word using contenttype

asp.net ms-word content-type

I have an Asp.net page, and I'd like to send it's content (ie. the rendered page) to open in Microsoft Word. I have the below code in my Page_Load event.

STL vector and thread-safety

c++ multithreading stl vector thread-safety

Let's say I have a vector of N elements, but up to n elements of this vector have meaningful data. One updater thread updates the nth or n+1st element (then sets n = n+1), also checks if n is too c...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.