在R中创建用户定义的函数,其中包含一个列表而不仅仅是一个输入



我想创建可以使用多个输入进行测试的函数,例如下面是我的代码中的数字列表。我不仅想测试几个输入,但我不知道如何在函数参数中做同样的事情。

grads<-function((for (X in 0:100)))

if (x<=50){
"Fail"
}else if (x<=70){
"Good"

}else if (x<=80){
"V Good"
} else {
"Execellent"
}
grads(95,60,77,33)

这是错误,我得到

Error in grads(95, 60, 77, 33) : unused arguments (60, 77, 33)

我们可以用data.table中的fcase

library(data.table)
grads <- function(x) {
data.table::fcase(x <= 50, "Fail",
x <= 70, "Good",
x <= 80, "Very Good",
default = "Excellent")
}

测试

grads(c(95,60,77,33))
[1] "Excellent" "Good"      "Very Good" "Fail"  

或从base R使用findInterval

grads <- function(x)  {
c("Fail", "Good", "Very Good", "Excellent")[findInterval(x,
c(0, 50, 70, 80, 100))]
}
grads(c(95,60,77,33))
[1] "Excellent" "Good"      "Very Good" "Fail"    

您需要使用向量化函数来处理多个值。

这里有一些选项。

  1. 嵌套ifelse.
grads<- function(x) {
ifelse(x <= 50, "Fail", 
ifelse(x <= 70, "Good", 
ifelse(x <= 80, "Very Good", "Excellent")))
}
grads(c(95,60,77,33))
#[1] "Excellent" "Good"      "Very Good" "Fail" 
  1. case_whenfromdplyr,这对于嵌套条件更容易读
grads<- function(x) {
dplyr::case_when(x <= 50 ~ "Fail", 
x <= 70 ~ "Good", 
x <= 80 ~ "Very Good",
TRUE ~ "Excellent")
}
grads(c(95,60,77,33))
  1. cut可伸缩
grads<- function(x) {
cut(x, c(0, 50, 70, 80, 100), c("Fail", "Good", "Very Good", "Excellent"))
}
grads(c(95,60,77,33))

相关内容

  • 没有找到相关文章

最新更新