Question

I have a list of student grades in a spreadsheet, and I'd like to convert the grades into numbers. So, for instance, change an "A" to "1" and "C" to "3". And I'd like it to go into a separate column.

Grade variable is named "CRSE_GRADE_OFF"

I'm running Rstudio 0.98 on Mac OS 10.8.5.

thank you

Was it helpful?

Solution

Often you can use a named vector to do these sorts of mapping operations simply:

students <- data.frame(name=c("J. Holly","H. Kally", "P. Spertson", "A. Hikh", "R. Wizht"),
                       CRSE_GRADE_OFF=c("A","D","E","A","A"))
scores = c(A=1, B=2, C=3, D=4, E=5, F=6)
students$grade <- scores[as.character(students$CRSE_GRADE_OFF)]
students
#          name CRSE_GRADE_OFF grade
# 1    J. Holly              A     1
# 2    H. Kally              D     4
# 3 P. Spertson              E     5
# 4     A. Hikh              A     1
# 5    R. Wizht              A     1

If you wanted to keep with Ben Bolker's as.numeric solution, you could explicitly set the possible levels of the CRSE_GRADE_OFF factor:

students$CRSE_GRADE_OFF <- factor(students$CRSE_GRADE_OFF,
                                  levels=c("A", "B", "C", "D", "E", "F"))
students$grade <- as.numeric(students$CRSE_GRADE_OFF)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top