I want to create functions that I can test with multiple inputs such as a list of numbers below is my code. I want to test several inputs not only but I do not how to do the same in the function argument.
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)
this is error that I got
Error in grads(95, 60, 77, 33) : unused arguments (60, 77, 33)
CodePudding user response:
We can use fcase
from data.table
library(data.table)
grads <- function(x) {
data.table::fcase(x <= 50, "Fail",
x <= 70, "Good",
x <= 80, "Very Good",
default = "Excellent")
}
-testing
grads(c(95,60,77,33))
[1] "Excellent" "Good" "Very Good" "Fail"
Or using findInterval
from base R
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"
CodePudding user response:
You need to use vectorized functions to work with more than one value.
Here are some options.
- Nested
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"
case_when
fromdplyr
which is more readable for nested conditions
grads<- function(x) {
dplyr::case_when(x <= 50 ~ "Fail",
x <= 70 ~ "Good",
x <= 80 ~ "Very Good",
TRUE ~ "Excellent")
}
grads(c(95,60,77,33))
cut
which is scalable.
grads<- function(x) {
cut(x, c(0, 50, 70, 80, 100), c("Fail", "Good", "Very Good", "Excellent"))
}
grads(c(95,60,77,33))