Skip to content

Instantly share code, notes, and snippets.

@jsta
Created April 9, 2018 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsta/707bfe7b025dfb4a805b2c473a2378e7 to your computer and use it in GitHub Desktop.
Save jsta/707bfe7b025dfb4a805b2c473a2378e7 to your computer and use it in GitHub Desktop.
Fitting bayesian power law model in stan
library(rstan)
a <- 50
b <- 1
N <- 100
x <- 1:N
y <- a * x^b
y <- y + rexp(1:100, 0.01)
model_code <- '
data {
int<lower=0> N;
vector[N] x;
vector[N] y;
}
parameters {
real a;
real b;
real<lower=0> sigma;
}
model {
b ~ normal(1, 0.5);
a ~ normal(50, 20);
sigma ~ exponential(0.01);
{
vector[N] mu;
for (i in 1:N) mu[i] <- a * x[i] ^ b;
y ~ normal(mu, sigma);
}
}
'
estimate.model <- function(x, y) {
N <- length(x)
data <- list(N = N, x = x, y = y)
fit <- stan(model_code = model_code, data = data)
return(fit)
}
fit <- estimate.model(x, y)
print(fit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment