Hi,
I’m just trying to get my head around building models, and this is not working. I think you can see what I’m trying to do and I’m pretty sure the problem is in the loop in the transformed parameters block. Data setup with lm and plots up front. Thanks for your help:
library(tidyverse)
library(rstan)
library(shinystan)
n <- 50
j <- 3
beta <- 2
#noise <- rnorm(length(x), mean=0, sd=10)
x <- (1:n)
account <- (1:j)*20;
likeData <- data.frame(y = as.numeric(), x = as.numeric(), account = as.numeric())
for(i in 1:j){
y = account[i] + beta*x + rnorm(length(x), mean=0, sd=10)
tmpDF <- data.frame(y=y, x=x, account = account[i])
likeData <- rbind(likeData, tmpDF)
}
likeData$account <- as.factor(likeData$account)
p <- ggplot(likeData, aes(x, y, color = account))+geom_point()
p
lmMod <- lm(y ~ x + account, data=likeData)
summary(lmMod)
ggplot(likeData, aes(x=account, y=y))+geom_boxplot()
stanModel <- '
data {
int<lower = 0> N;
int<lower = 0> J;
vector[N] account;
vector[N] y;
vector[N] x;
}
parameters {
vector[J] alpha;
real beta;
real alphaMu;
real alphaSigma;
real ySigma;
}
transformed parameters {
vector[N] yMu;
for(i in 1:J) {
yMu = alpha[i] + beta*x;
}
}
model {
// prior
alphaSigma ~ uniform(0,100);
alpha ~ normal(alphaMu, alphaSigma);
beta ~ normal(0, 10);
// likelihood
ySigma ~ uniform(0,100);
y ~ normal(yMu, ySigma);
}
'
stanData <- list(
N=nrow(likeData),
J=nlevels(likeData$account),
account = as.integer(likeData$account),
y=likeData$y,
x=likeData$x
)
fit <- stan(model_code = stanModel, data = stanData)
[Edit: Escaped code]