A function to assign grade based on the score

# creating a reprex of kyle's code ----------------------------------------
# A function to assign grade based on the score 

library(tibble)
score <- c(rnorm(20, 80, 5))
# grade <- c(LETTERS[1:4, 6])
raw.df <- tibble(score)

for (i in 1:nrow(raw.df)) {
  if (is.na(raw.df$grade[i])) {
    if (raw.df$score[i] > 80) {
      raw.df$grade[i] <- "A"
    } else {
      raw.df$grade[i] <- "B"
    }
  }
}
#> Warning: Unknown or uninitialised column: `grade`.
#> Error in if (is.na(raw.df$grade[i])) {: argument is of length zero

to fix your code you would add raw.df$grade<-NA before the fore loop
or use an alternative approach

library(dplyr)
(raw.df2 <- tibble(score) %>% mutate(grade=
                                      case_when(score>80 ~ "A",
                                                    TRUE ~ "B")))
1 Like

Sorry for the long delay, apparently the site was down for a day?
Here's an alternate base R solution.

x <- sample(40:100, 60, TRUE)
grade <- function(x,
                  grades = c("F", "D", "C", "B", "A"),
                  bound = c(-Inf, 60, 70, 80, 90, Inf)) {
           cut(x, bound, grades)
}
df <- data.frame(raw_score = x, grade = grade(x))
head(df)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.