我想要一个if语句,当语句为NULL或字符串等效时执行:
somefun <- function (number1, number2, type=NULL) {
if (is.null(type) | type == "sum") {
print(number1+number2)
} else if (type == "product") {
print(number1*number2)
}}
# So that the two following lines lead to the same result
somefun(1,4)
somefun(1,4,type="sum")
然而,第一个给出了错误:
Error in if (is.null(type) | type == "sum") { :
argument is of length zero
我应该如何编写语法?
这是您需要使用||
的实例之一|
somefun <- function (number1, number2, type=NULL) {
if (is.null(type) || type == "sum") {
print(number1+number2)
} else if (type == "product") {
print(number1*number2)
}
}
> somefun(1,4,type="sum")
[1] 5
> somefun(1,4,type=NULL)
[1] 5
> somefun(1,4)
[1] 5
如果我能提出一个建议:
somefun2 <- function (number1, number2, type=NULL){
if(is.null(type)){
type <- "sum"
}
switch(type,
"sum" = number1 + number2,
"product" = number1 * number2
)
}