Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the default value in a function?

I have a simple density function below:

dpower <- function(x, b, r){ if ((b <= 0 | r <= 0))  return("Wrong parameters entered!") else{  density.temp <- (r/b)*(x/b)^(r - 1)  density.temp[which(x >= b | x <= 0)] <- NA  return(density.temp)  }  } 

This function returns density corresponding to value x from the specified distribution with parameters b and r. I'd like to set the default value on x that if the user doesn't specify x, the default values passes through. We can simply set dpower <- function(x = x.default, b, r)... however, my default value depends on r and b. How can I do that? suppose the default value for x is:

seq(from = 0.05, to = b, by = 0.001) 

Thanks for your help,

like image 424
Sam Avatar asked Nov 16 '12 04:11

Sam


People also ask

How do you define a function with default value?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

How do you set a default argument in a function?

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.

Can functions have default values?

We can also use a function as a default value. Functions are first-class citizens in JavaScript and can be treated like any other variable. We can set a default value by evaluating a function and using the value returned.


2 Answers

dpower <- function(b, r, x = seq(from = 0.05, to = b, by = 0.001)) .... 
like image 172
Matthew Lundberg Avatar answered Sep 20 '22 17:09

Matthew Lundberg


You can set the value of X to NULL and have one of the first lines of your function be

 if(is.null(x))      x <- seq(from = 0.05, to = b, by = 0.001) 
like image 38
Ricardo Saporta Avatar answered Sep 21 '22 17:09

Ricardo Saporta