0

I am running an ordinal logit model with brms package. I want to write the density of the posterior distribution of the parameters.

<model>

    dfpop$pop = factor(df$pop, levels = c("extinct","<10", "<100", "<1000", ">=1000"), ordered = TRUE) 
dfpop$RDB2000pop = factor(dfpop_chenv$RDB2000pop, levels = c("<10", "<100", "<1000", ">=1000"), ordered = TRUE) 
bmodel<- brms::brm(pop ~  R2000pop + Temperature2003 + Population2003 + Volcanic.area + Agricultural.land2003 + RiverLake2003 + Seashore2003 + Protected.area + 
                         (1+RDB2000pop+Temperature2003+Population2003+ Volcanic.area + Agricultural.land2003 + RiverLake2003 + Seashore2003 + Protected.area |species_id),
             data      = dfpop,
             family    = "cumulative",
             prior   = c(set_prior("normal(0,10)", class = "b")), 
             warmup    = 200,
             iter      = 1000,
             chains    = 4,
             save_all_pars = TRUE) 

I was able to build the model, but I am only able to create one plot at a time. The following code tried to run the loop function by giving variable names. However, I could not draw the density in the result obtained.

<plot>

model1tranformed <- ggs(bmodel)

exvars <- rownames(summary(bmodel)$fixed)

plots <- list()
for(i in 1:length(exvars)){
p<-ggplot(filter(model1tranformed,
              Parameter  %in% c("exvars[i]"), 
              Iteration > 0),
       aes(x = value))+
  geom_density(fill  = "darkgreen", 
               alpha = .5)+
  geom_vline(xintercept = 0, 
             col  = "darkred",
             size = 1)+
  scale_x_continuous(name   = "Value",
                     limits = c(-10,10)) + 
  geom_vline(xintercept = summary(bmodel)$fixed[i,3:4],
             col = "blue",
             linetype = 2) +
  theme_light() +
  theme(text = element_text(size = 20))
  labs(title = paste("pd_",exvars[i]))
  plots[[i]] = p
}
library(gridExtra)
pp <- do.call("grid.arrange", c(plots, ncol=4))
ggsave(pp)

enter image description here

marie
  • 315
  • 1
  • 9
  • Hard to say without more data and insight into your data structures, but I would venture a guess at your line `Parameter %in% c("exvars[i]")` -- this effective ensures that the result of the `filter`-call in the loop is always the same. Perhaps it should be `Parameter %in% exvars[i]`? – MrGumble Aug 04 '21 at 07:41
  • 1
    You are a vioctim of lazy evaluation. When your `do.call` is executed, `i` is equal to `length(exvars)` and hence your plots are identical. Change your `for` loop to (eg) `lapply`, which forces evaluation, and all will be well. There are answers to many, many similar questions on SO that illustate possible solutions. – Limey Aug 04 '21 at 07:55
  • Thank you a lot. This problem has been solved. The problem was with the data shaping, not with the loop function. Sorry about that. I would like to use the lapply function more actively from now on. – marie Aug 05 '21 at 01:53

0 Answers0