意外的'{'和'else'

问题描述 投票:0回答:1

[试图创建一个可以保存“分数”向量的函数,然后该函数将确定分数的定性等级。我已经多次重新排列了括号,但仍然遇到这些错误。同样,“ else”也出现错误。

    credit_fun <- function(scores){
      if (scores>300 & scores<579)(incbounds = TRUE){
    'Very Poor';
    } else if (scores>580 & scores<669)(incbounds = TRUE){
    'Fair';
    } else if (scores>670 & scores<739)(incbounds = TRUE){
    'Good';
    } else if (scores>740 & scores<799)(incbounds = TRUE){
    'Very Good';
    } else if (scores>800 & scores<850)(incbounds = TRUE){
    'Exceptional'}
}
r if-statement curly-braces
1个回答
0
投票

我们可以使用betweencase_when

library(dplyr)
credit_fun <- function(scores) {
      case_when(between(scores, 300, 579) ~ "Very Poor",
                between(scores, 580, 669) ~ "Fair",
                between(scores, 670, 739) ~ "Good",
                between(scores, 740, 779) ~ "Very Good", 
                TRUE ~ "Exceptional")

  }

或者另一个选项是cut

credit_fun <- function(scores) {
           cut(scores, breaks = c(-Inf, 300, 580, 670, 740, Inf),
                 labels = c("Very Poor", "Fair", "Good", "Very Good", "Exceptional"))
  }

或带有findInterval

credit_fun <- function(scores) {
   c("Very Poor", "Fair", "Good", "Very Good", "Exceptional")[findInterval(scores, 
                 c(300, 580, 670, 740))]
  }
© www.soinside.com 2019 - 2024. All rights reserved.