Trouble Installing rstan on macOS Monterey. keep getting errors

I mainly get this error when running

install.packages("rstan")

Warning in install.packages :
installation of package ‘rstan’ had non-zero exit status

and after trying a few things am also getting this error when I’m running my code:

k <- seq(-1, 20)
##make a data frame with all the k and posterior mean. 
posterior_results <- data.frame(k = numeric(length(k)), posterior_mean = numeric(length(k)))

for (i in 1:length(k)) {
  data.in2a <- list(yi = y2, mi = m2, n = length(m2), k = k[i])
  model.fit2a <- sampling(q2a, data = data.in2a, iter = 10)
  posterior_samples_summary <- summary(model.fit2a)
  posterior_mean <- posterior_samples_summary$summary["p", "mean"]
  posterior_results[i, ] <- c(k = k[i],posterior_mean = posterior_mean)
 
}

Error in prep_call_sampler(object) : could not find function “prep_call_sampler”

  1. object@mk_cppmodule(object)

  2. .local(object, …)

  3. sampling(q2a, data = data.in2a, iter = 10)

  4. sampling(q2a, data = data.in2a, iter = 10)

Can you close and restart R, making sure that no packages or code is loaded and then run:

install.packages(c("rstan","StanHeaders"), type ="source")