rrstan

The extract() function does not handle a stanfit object, am I using it wrong?


I have the (simplified) code below where I fit a model using rstan. The code was provided in a computer lab assignment. Earlier today I ran the whole file and everything ran fine, but now the extract() function returns an error: Error in extract(fit) : object of type 'S4' is not subsettable.

library(rstan)
y=c(1:10)
N=length(y)

StanModel = '
data {
  int<lower=0> N; // Number of observations
  int<lower=0> y[N]; // Number of flowers
}
parameters {
  real mu;
}
model {
  mu ~ normal(0, 1);
  for(i in 1:N){
    y[i] ~ normal(mu, 1);
  }
}'

data <- list(N=N, y=y)
fit <- stan(model_code=StanModel, data=data, warmup=0, iter=50, chains=1)

# Extract posterior samples
postDraws <- extract(fit)

I have cleared the environment, and as far as I can tell I am using the function correctly according to my lab instructions and the Stan development team docs. What I am expecting is "a list with named components corresponding to the model parameters".

Edit: I found out that as.matrix() works and provides me with the posterior samples, but the question remains why extract() raises an error.


Solution

  • As suggested by Marco Sandri in a comment above, the issue was that I was using the magrittr::extract function, and not the rstan::extract function. Specifying the package solved the problem.