HBat
HBat

Reputation: 5682

A general way to enter prior distribution information into function?

I want to enter prior distribution information into a function. I can enter individual distributions manually by modifying function body but I'm searching for a general way of doing this? For example, I want to plot posterior distribution of a function given prior distribution.

set.seed(1)
n <- 10
pars <- runif(n)
y <- NA
for (i in 1:n)
  y[i] <- rbinom(1,1, prob=pars[i])

plotPosterior <- function(pars,y,mean=0,vari=4)
{  
  x <- seq(-3,3,by = .1)
  logLik <- NA
  for (i in seq(along.with=x))
    logLik[i] <- sum(y*log(1 + exp(pars-x[i])) - (y-1)*log(1 + exp(x[i]-pars)))

  posterior <- logLik * dnorm(x,mean=mean,sd=sqrt(vari))
  plot(x,posterior,type="l")
}
plotPosterior(pars,y,0,4) 

I can able to enter mean an variance parameters for normal distribution. But if I want to use, for example, beta distribution I have to rewrite the function. Instead I want a way to enter distributions like "dnorm(mean=xx,sd=yy)" or "dbeta(shape1=xx, shape2=yy)"...
Only viable way I see is entering dnorm(x,mean=mean,sd=sqrt(vari)) into function as an input. But I don't want to pre-specify x beforehand. Is there any other way to do this?

Upvotes: 1

Views: 595

Answers (1)

baptiste
baptiste

Reputation: 77096

For the sake of clarity, here's a working solution extracted from the comments,

set.seed(1)
n <- 10
pars <- runif(n)
y <- NA
for (i in 1:n)
  y[i] <- rbinom(1,1, prob=pars[i])

plotPosterior <- function(pars,y, fun = dnorm, 
                          params.fun = list(mean=0, sd=2))
{  
  x <- seq(-3,3,by = .1)
  logLik <- NA
  for (i in seq(along.with=x))
    logLik[i] <- sum(y*log(1 + exp(pars-x[i])) - (y-1)*log(1 + exp(x[i]-pars)))

  posterior <- logLik * do.call(fun, c(list(x), params.fun))
  plot(x,posterior,type="l")
}

plotPosterior(pars, y) # default params and function
plotPosterior(pars, y, fun = dbeta, params.fun = list(shape1=2, shape2=3))

Upvotes: 1

Related Questions