Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pairs.stanfit delays arguments evaluation in a way that breaks lexical scoping. #1155

Open
iago-lito opened this issue Feb 26, 2025 · 0 comments

Comments

@iago-lito
Copy link

The following script errors in a very confusing way:

library(rstan)

#================================================================================
# Produce two dummy `stanfit` objects

model <- rstan::stan_model(model_code = r"(
  data {
    int<lower=0> N;
    array[N] int<lower=0, upper=1> y;
  }
  parameters {
    real<lower=0, upper=1> theta;
  }
  model {
    // uniform prior on interval 0,1
    theta ~ beta(1, 1);
    y ~ bernoulli(theta);
  }
)")

data <- list(
  a = round(runif(10, 0, 1)),
  b = round(runif(15, 0, 1))
)

fits <- lapply(data, function(y) {
    rstan::sampling(model, data = list(y = y, N = length(y)))
})

#================================================================================
# Plot from within a closure:

plot_function <- function() {
  for (name in names(fits)) {
    print(name) # Correctly prints "a".
    pairs(fits[[name]], main = name)
  }
}
pdf("test.pdf")
plot_function() # Error: object 'name' not found
dev.off()

From what I understand, pairs.stanfit, for some reason, does not evaluate its main = name argument within the context of the enclosing closure, but within the global scope instead. This was the source of a very nasty bug difficult to hunt down.

As far as I can check, this is not the expected/common behaviour of pair, and the problem does not happen, with, say:

pairs(data.frame(x = runif(10, 1, 10), y = runif(10, 1, 10)), main = name)

instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant