Error when passing factor data to Stan

Whenever I try to pass data to Stan that is a factor, I’m getting the below error. This must be a new change because this worked before.

m <- cmdstanr::write_stan_file("data { array[10] int x; }") |> 
  cmdstanr::cmdstan_model() 
m$sample(data = lst(x = factor(1:10)), fixed_param = TRUE)

produces

Error in Math.factor(1:10) : ‘round’ not meaningful for factors

Operating System: Linux
Interface Version: cmdstanr 0.8.1.9000
Compiler/Toolkit: 2.35.0

Stan doesn’t support factor data types. You have specified x as array of int.
If you have a factor you may convert it in GNU R with as.numeric(f) with f factor.

These factor types used to be implicitly converted to integers before which seems reasonable. Anyone passing a factor probably wants their IDs passed to the model. Not sure why rounding is now being applied to them now.

You should not pass a factor to a model. Instead translate your factor levels to
integers and then use these values in Stan. In other word, you have to handle
the factor levels as integers in Stan by yourself.

I assume they are treated as real values. But it’s not a bug, since Stan doesn’t support
factors.

This just an inconvenience really so not a big issue. The reason I report is that it used to work in the more reasonable way of converting factors to integers not reals. Yes, I know Stan doesn’t support factors directly.

Resolved in this PR. Please use the Github for bug reports in the future, otherwise it takes longer for me to see

1 Like

I will and thanks for your work making cmdstanr more awesome every day!