Reputation: 1735
Is there a way to do something like this in R?
doSomething <- function(a){
value <- NULL
if(a > 0){
value <- a
}
return(value)
}
doSomething(-5) | "no value"
I'm just making this up but was curious to know if something like this or similar is possible to do using R instead of using ifelse/switch/case_when
?
Upvotes: 1
Views: 53
Reputation: 44788
There's no built in syntax for that, but you can write your own. For example, internally knitr
uses
`%n%` = function(x, y) if (is.null(x)) y else x
and then your example becomes
doSomething <- function(a){
value <- NULL
if(a > 0){
value <- a
}
return(value)
}
`%n%` <- function(x, y) if (is.null(x)) y else x
doSomething(-5) %n% "no value"
#> [1] "no value"
Created on 2020-05-06 by the reprex package (v0.3.0)
Watch out though: in R, there are many different ways to have no value: something could be missing, or NA
, or NaN
, as well as NULL
.
Upvotes: 2
Reputation: 3923
I'm confused. Do you want to do this?
doSomething <- function(a){
value <- "no value"
if(a > 0){
value <- a
}
return(value)
}
doSomething(-5)
#> [1] "no value"
doSomething(5)
#> [1] 5
Created on 2020-05-06 by the reprex package (v0.3.0)
Upvotes: 0
Reputation: 2143
Not really.
NULL is a list. For doSomething
, argument a
is numeric.
doSomething(3) | "no value"
would OR a number with a character, which is not defined. You can do that kind of thing in Perl, but it's more a bug than a feature.
Upvotes: 0