Very simple question. Is there any disadvantage to using the 2nd approach outlined below versus approach 1? Or are they effectively identical. (I'm partial to approach 2 as I deal with some complicated conditioning of variables, and find it easier to track piping the variable from one line to the next, but concerned that it might be poor coding practice)
library(dplyr)
section <- c("MATH111", "MATH111", "ENG111")
grade <- c(78, 93, 56)
student <- c("David", "Kristina", "Mycroft")
gradebook <- data.frame(section, grade, student)
mutate(gradebook, Pass.Fail = ifelse(grade > 60, "Pass", "Fail"))
#approach 1
mutate(gradebook, letter = ifelse(grade %in% 60:69, "D",
ifelse(grade %in% 70:79, "C",
ifelse(grade %in% 80:89, "B",
ifelse(grade %in% 90:99, "A", "F")))))
#approach 2
gradebook$letter<-NA
gradebook <- gradebook %>%
mutate(letter=ifelse(grade < 60, "F",letter)) %>%
mutate(letter=ifelse(grade >60 & grade< 69, "D",letter)) %>%
mutate(letter=ifelse(grade >70 & grade< 79, "C",letter)) %>%
mutate(letter=ifelse(grade >80 & grade< 89, "B",letter)) %>%
mutate(letter=ifelse(grade >90 & grade< 99, "A",letter))
gradebook
It seems there are some typo, but if you try using dplyr::mutate
, in this case, dplyr::case_when
will helps.
gradebook %>%
mutate(letter = case_when(
grade < 60 ~ "F",
grade < 70 ~ "D",
grade < 80 ~ "C",
grade < 90 ~ "B",
grade < 100 ~ "A",
T ~ NA_character_
))
section grade student letter
1 MATH111 78 David C
2 MATH111 93 Kristina A
3 ENG111 56 Mycroft F
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.