I have two dataframes:
marks<-data.frame("student" =c("stud1","stud2","stud3") ,"sub1" =c(25,75,43), "sub2" = c(43,99,45),"sub3" = c(32,53,45), stringsAsFactors = FALSE)
grades<-data.frame("grade" =c("F","B","A") ,"sub1" =c(50,75,85), "sub2" =c(35,75,85)),"sub3" =c(32,75,85), stringsAsFactors = FALSE)
(sample in image format as well)
I need to compare each mark in Marks df and get corresponding grades from Grades df. The grade definition is different for different subjects. I have tried using lapply function and cut:
(marks<-sapply(marks, function(x) cut(x,
breaks=c(0,50,75,85),
labels=c("F","B","A"),include.lowest = TRUE, right = TRUE,na.rm = TRUE))
This works without difficulty if grade boundaries are fixed. But when they change dynamically (based on subject column) I could not do this.
The expected output is:
gradedmarks<-data.frame("student" =c("stud1","stud2","stud3") ,"sub1" =c("F","B","F"), "sub2" = c("F","A","F"),"sub3" = c("F","F","F"), stringsAsFactors = FALSE)
Any quick way to achieve this in R?
Please note this is NOT the duplicate of this(Looping through multiple if_else statements). This is about using cut function with dynamic values depending on the column.