如何为函数内的参数定义值的等级?
how to define a rank of values for an argument inside a function?
让我们假设下一个函数:
demo_function <- function(x){
if(is.na(x)){
return(NA)
} else if(1 < x < 2){
return("something")
} else {
return("Nothing")
}
}
想法是,当参数 x
介于 1 和 2 之间时,比如 x=0.001
,然后函数 returns something.
但是当尝试运行上述函数时,出现下一个错误:
Error: no function to go from, jumping to a higher level
如何调整函数以获得指定参数的 "something"
?
问题出在 else if
中,即 R
中的语法与数学符号不同 - 多个表达式由逻辑运算符连接
else if(1 < x && x < 2)
即
demo_function <- function(x){
if(is.na(x)){
return(NA)
} else if(1 < x && x < 2){
return("something")
} else {
return("Nothing")
}
}
> demo_function(0.01)
[1] "Nothing"
> demo_function(1.5)
[1] "something"
> demo_function(NA)
[1] NA
让我们假设下一个函数:
demo_function <- function(x){
if(is.na(x)){
return(NA)
} else if(1 < x < 2){
return("something")
} else {
return("Nothing")
}
}
想法是,当参数 x
介于 1 和 2 之间时,比如 x=0.001
,然后函数 returns something.
但是当尝试运行上述函数时,出现下一个错误:
Error: no function to go from, jumping to a higher level
如何调整函数以获得指定参数的 "something"
?
问题出在 else if
中,即 R
中的语法与数学符号不同 - 多个表达式由逻辑运算符连接
else if(1 < x && x < 2)
即
demo_function <- function(x){
if(is.na(x)){
return(NA)
} else if(1 < x && x < 2){
return("something")
} else {
return("Nothing")
}
}
> demo_function(0.01)
[1] "Nothing"
> demo_function(1.5)
[1] "something"
> demo_function(NA)
[1] NA