Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to use a "null" default value for an argument of a function?

Here is my current code:

my.function <- function( my.arg="" ){
  if(my.arg == "")
    my.arg <- rnorm(10)
  return( mean(my.arg) )
}

It returns me this:

> my.function( rbinom(10, 100, 0.2) )
[1] 18.5
Warning message:
In if (a == "") a <- rnorm(10) :
  the condition has length > 1 and only the first element will be used

I tried with my.arg=c(), or my.arg=0, but I always get either a warning or an error. And the R manual doesn't say much on this issue.

Any idea? Thanks in advance!

like image 445
tflutre Avatar asked Jul 01 '11 20:07

tflutre


People also ask

How do you pass a default value for an argument in R?

First time, function is called with single argument and default value is used for second argument. Function called successfully and produce a result. Second time, function is called with two arguments, default value of second argument is overridden.

How will you specify a default value for an argument in the function definition?

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.

Can a function argument have default value?

Any number of arguments in a function can have a default value.

How can we pass default arguments to a function?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


2 Answers

try

my.function <- function( my.arg=NULL ){
 if(is.null(my.arg)) ...
like image 100
Karsten W. Avatar answered Nov 16 '22 02:11

Karsten W.


There's also missing:

my.function <- function(my.arg) {
  if(missing(my.arg)) ...
like image 22
Aaron left Stack Overflow Avatar answered Nov 16 '22 02:11

Aaron left Stack Overflow