user12996093
user12996093

Reputation: 13

Unexpected '{' and 'else'

Trying to make a function where a vector for "scores" can be saved, and then this function would determine the qualitative rating of the score. I've rearranged my brackets multiple times, but I still get those errors. Also getting errors with the "else" as well.

    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'}
}

Upvotes: 1

Views: 64

Answers (1)

akrun
akrun

Reputation: 887501

We could use between and 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")

  }

Or another option is cut

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

Or with findInterval

credit_fun <- function(scores) {
   c("Very Poor", "Fair", "Good", "Very Good", "Exceptional")[findInterval(scores, 
                 c(300, 580, 670, 740))]
  }

Upvotes: 1

Related Questions