Skip to content

Instantly share code, notes, and snippets.

@ito4303
Last active Mar 6, 2019
Embed
What would you like to do?
Dealing with rounded data in Stan
---
title: "Rounding"
output: html_notebook
---
```{r}
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
```
# Model
https://mc-stan.org/docs/2_18/stan-users-guide/bayesian-measurement-error-model.html
```{stan, output.var=rounding}
data {
int<lower=0> N;
vector[N] y;
}
parameters {
real mu;
real<lower=0> sigma_sq;
vector<lower=-0.5, upper=0.5>[N] y_err;
}
transformed parameters {
real<lower=0> sigma;
vector[N] z;
sigma = sqrt(sigma_sq);
z = y + y_err;
}
model {
target += -2 * log(sigma);
z ~ normal(mu, sigma);
}
```
# Run Stan
```{r}
set.seed(12)
y <- rnorm(20, 10, 2)
y_r <- round(y, 0)
N <- length(y)
fit <- sampling(rounding, data = list(N = N, y = y_r))
print(fit)
plot(fit, pars = "y_err")
```
```{r}
df <- data.frame(Y = rep(y, 2),
Y2 = c(y_r, get_posterior_mean(fit, pars = "z")[, "mean-all chains"]),
Var = rep(c("Rounded", "Estimated"), each = length(y)))
ggplot(df) +
geom_point(aes(x = Y, y = Y2, colour = Var)) +
geom_abline(aes(slope = 1, intercept = 0), colour = "gray") +
labs(x = "True", y = "Rounded and estimated") +
coord_fixed()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment