简体   繁体   English

使用 mutate() 和 ifelse()

[英]Using mutate() and ifelse()

Very simple question.很简单的问题。 Is there any disadvantage to using the 2nd approach outlined below versus approach 1?与方法 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) (当我处理一些复杂的变量条件时,我偏爱方法 2,并且发现更容易跟踪从一行到下一行的变量,但担心这可能是糟糕的编码实践)

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.似乎有一些错字,但是如果您尝试使用dplyr::mutate ,在这种情况下, dplyr::case_when会有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM