【问题标题】:create user defined function in R with a list not only one inputs在 R 中创建用户定义的函数,其中包含一个列表,而不仅仅是一个输入
【发布时间】:2021-12-04 14:36:30
【问题描述】:

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

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)

【问题讨论】:

    标签: r function


    【解决方案1】:

    我们可以从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 RfindInterval

    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"    
    

    【讨论】:

      【解决方案2】:

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

      这里有一些选项。

      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_when from dplyr 对于嵌套条件更具可读性
      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))
      

      【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2020-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 2019-12-20
        相关资源
        最近更新 更多