user1828605
user1828605

Reputation: 1735

Simple function call in R

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

Answers (3)

user2554330
user2554330

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

Chuck P
Chuck P

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

David T
David T

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

Related Questions