Sam
Sam

Reputation: 4497

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,

Upvotes: 34

Views: 73953

Answers (2)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

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)

Upvotes: 11

Matthew Lundberg
Matthew Lundberg

Reputation: 42629

dpower <- function(b, r, x = seq(from = 0.05, to = b, by = 0.001))
....

Upvotes: 47

Related Questions