Setting the default value in a function?

Sam picture Sam · Nov 16, 2012 · Viewed 51k times · Source

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,

Answer

Matthew Lundberg picture Matthew Lundberg · Nov 16, 2012
dpower <- function(b, r, x = seq(from = 0.05, to = b, by = 0.001))
....