For 循环检索超过 1 个 return 值(维数不正确)

For loop retrieving more than 1 return value (incorrect number of dimensions)

我正在尝试根据需要创建一个 returns 多个值(可以处理任意长度)的循环。

ltrGrades <- (0:100)

numGrades <- character(length(ltrGrades))

for (i in 1:length(ltrGrades ))
  if(any(ltrGrades[i] == 91:100)) {
    numGrades[i] <- "A"
  } else if (any(ltrGrades[i] == 80:90)) {
    numGrades[i] <- "B"
  } else if (any(ltrGrades[i] == 70:79)) {
    numGrades[i] <- "C"
  } else if (any(ltrGrades[i] == 60:69)) {
    numGrades[i] <- "D"
  } else if (any(ltrGrades[i] == 0:59)) {
    numGrades[i] <- "F"
  }

numGrades[98]
numGrades[82]
numGrades[76]
numGrades[61]
numGrades[98, 82, 76, 61]
Error in numGrades[98, 82, 76, 61] : incorrect number of dimensions

您可以使用用户定义的函数并应用

grading <- function(x)
{
  grades <- cut(x, 
                        breaks=c(0,seq(60,100,by=10)),
                        labels=c("F","D","C","B","A"))
  return(grades)
}

## your list of scores #####
score<- c(50,40,70,80,90)

##sapply to find the grades #######
sapply(score,grading)