There is no need for ifelse
, you could do the following:
df$numericGrade = NA
df$numericGrade[df$grade=="A"] = 13
df$numericGrade[df$grade=="A-"] = 12
df$numericGrade[df$grade=="B+"] = 11
df$numericGrade[df$grade=="C-"] = 6
For example:
df = data.frame(Name = c("John", "Mary", "Timmy", "Susan"), grade = c("B+", "A", "C-", "DNF"))
Name grade
1 John B+
2 Mary A
3 Timmy C-
4 Susan DNF
applying the previous lines results in:
Name grade numericGrade
1 John B+ 11
2 Mary A 13
3 Timmy C- 6
4 Susan DNF NA
Of course this takes one line for every case and my example is not complete.
Using Merge
Another option is to use merge
. In this case you need to have another data frame with the grades conversion:
gradesDict = data.frame(letter = c("A", "A-", "B+", "C-"),
number = c(13, 12, 11, 6))
letter number
1 A 13
2 A- 12
3 B+ 11
4 C- 6
and then do:
df = merge(df, gradesDict, by.x = "grade", by.y = "letter", all.x = T)
grade Name number
1 A Mary 13
2 B+ John 11
3 C- Timmy 6
4 DNF Susan NA