R: Simplifying code to convert letter grades to numeric grades

前端 未结 3 623
孤街浪徒
孤街浪徒 2021-01-17 22:27

I have written a function in R that will convert a data frame containing letter grades into numeric grades. I then use sapply() on each column of the data frame. Is there a

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 23:12

    I would rewrite your convert_grades function as follows:

    convert_grades <- function(x) {
      A <- factor(x, levels=c("A+", "A", "A-",
                         "B+", "B", "B-",
                         "C+", "C", "C-",
                         "D+", "D", "D-", "F"))
      values <- c(4.3, 4, 3.7, 
                  3.3, 3, 2.7,
                  2.3, 2, 1.7,
                  1.3, 1, 0.7, 0)
      values[A]
    }
    

    Then, I would do the conversion like this:

    num_grades <- grades
    num_grades[] <- lapply(num_grades, convert_grades)
    num_grades
      final_exam quiz_avg homework_avg
    1        2.0      4.0            4
    2        1.7      2.7            4
    3        1.3      3.3            4
    4        3.3      3.3            4
    5        0.0      3.3            4
    6        3.0      3.7            4
    

提交回复
热议问题