[试图创建一个可以保存“分数”向量的函数,然后该函数将确定分数的定性等级。我已经多次重新排列了括号,但仍然遇到这些错误。同样,“ 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'}
}
我们可以使用between
和case_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))]
}