Reputation: 829
I want to find the largest grade of the failed subjects for students in R. I have written this function which works fine but it looks more like java code than R as it is traversing through vectors using loops instead of using special functions for that purpose in R. would you please suggest an alternative solution
grades <- c(62, 100, 45, 40, 46, 55, 56, 70)
largestFail <- function(grades){
location <- -1
faildFound <- FALSE
for(i in 1:length(grades)){
if(grades[i] < 50){
if(!faildFound) location <- i
if(grades[i] > grades[location]) location <- i
faildFound <- TRUE
}
}
return (location)
}
print (grades) # 5
Upvotes: 2
Views: 2743
Reputation: 1712
This works fine:
max(grades[grades < 50])
You subset the grades
vector to those values under 50, and then extract the maximum of it.
If you need detailed understanding, you can evaluate the parts separately:
grades < 50
returns a logical vector which is TRUE
for all values under 50grades[grades < 50]
then is a vector of all values under 50max()
around this vector to find the highest failing gradeIf you want to return -1 when no student failed, something like this should do the job:
grades <- c(60, 70, 80)
if(any(grades < 50)){
return(max(grades[grades < 50])
)
} else {
return(-1)
}
A shorter, but less clear, solution, would be to just append -1 to your vector of grades:
grades <- c(60, 70, 80)
grades <- c(grades, -1)
max(grades[grades < 50])
Upvotes: 8
Reputation: 24074
Another way, using which.max
but replacing the values above the threshold by NA
prior to the call:
which.max(replace(grades, grades>=50, NA))
#[1] 5
Upvotes: 3