R 我正在尝试根据另一列的分数为分数添加另一列

R 我正在尝试根据另一列的分数为分数添加另一列,r,dplyr,data-cleaning,tidy,R,Dplyr,Data Cleaning,Tidy,这是我尝试过的代码。我试着做一个函数,然后也使用它 best <- rest_tidy %>% mutate( graded = { if (rest_tidy$score < 14){ print("A") } if (between(rest_tidy$score, 14, 27)){ print("B") } if (rest_tidy$score > 27){

这是我尝试过的代码。我试着做一个函数,然后也使用它

best <- rest_tidy %>%
  mutate(
    graded = {
      if (rest_tidy$score < 14){
        print("A")
      }  if (between(rest_tidy$score, 14, 27)){
        print("B")
      }
      if (rest_tidy$score > 27){
        print("C")
      }
    }
  )

rest\u tidy
rest\u tidy使用
tidyverse

rest_tidy=data.frame(score=c(1,15,25,35,27,NA))
 rest_tidy %>%
   mutate(
     graded=case_when(score<14~"A",
                      score<=27~"B",
                      score>27~"C",
                      T~"Other"))
  score graded
1     1      A
2    15      B
3    25      B
4    35      C
5    27      B
6    NA  Other
rest\u tidy=data.frame(分数=c(1,15,25,35,27,NA))
休息时间%>%
变异(

分级=病例(得分与
tidyverse

rest_tidy=data.frame(score=c(1,15,25,35,27,NA))
 rest_tidy %>%
   mutate(
     graded=case_when(score<14~"A",
                      score<=27~"B",
                      score>27~"C",
                      T~"Other"))
  score graded
1     1      A
2    15      B
3    25      B
4    35      C
5    27      B
6    NA  Other
rest\u tidy=data.frame(分数=c(1,15,25,35,27,NA))
休息时间%>%
变异(

graded=case_when(score虽然对于此类场景,最好使用
case_when
if_else
之类的方法,只是为了好玩,对您的尝试进行一些修改实际上是可行的

rest_tidy=data.frame(score=c(1,15,25,35,27,NA))

best <- rest_tidy %>%
  rowwise() %>%
  mutate(
    graded = {
      if(is.na(score)) print("D")
      else if(score < 14) print("A")
          else if(between(score, 14, 27)) print("B")
            else print("C")
    }
  )
只有处理
na
案例的条件和触发多个
案例(如果需要)的正确嵌套。最后,
行式
确保每个元素都得到评估,而不仅仅是列的第一个元素


同样,这种方法可能有效,但不推荐使用。

虽然在这种情况下最好使用
case\u when
if\u else
之类的方法,但只是为了好玩,对您的尝试进行一些修改实际上是有效的

rest_tidy=data.frame(score=c(1,15,25,35,27,NA))

best <- rest_tidy %>%
  rowwise() %>%
  mutate(
    graded = {
      if(is.na(score)) print("D")
      else if(score < 14) print("A")
          else if(between(score, 14, 27)) print("B")
            else print("C")
    }
  )
只有处理
na
案例的条件和触发多个
案例(如果需要)的正确嵌套。最后,
行式
确保每个元素都得到评估,而不仅仅是列的第一个元素


同样,这种方法可能有效,但不推荐使用。

欢迎使用StackOverflow!请阅读有关的信息以及如何提供帮助。这将使其他人更容易帮助您。查看
案例\u when()
欢迎来到StackOverflow!请阅读有关和如何提供帮助的信息。这将使其他人更容易帮助您。查看
case\u when()
  score graded
  <dbl> <chr> 
1     1 A     
2    15 B     
3    25 B     
4    35 C     
5    27 B     
6    NA D