## Seed production model seed_frame = read.csv("light_exp_seed.csv") seed_data = seed_frame str(seed_data) library("R2jags") range(seed_data$biomass) # data1 = list(seeds = seed_data$seeds, mass = seed_data$biomass) #data1=list(seeds = c(seed_data$seeds[1:24], rep(NA, times = 61)), mass = c(seed_data$biomass[1:24], c(0.5, seq(1, 60, 1)))) # OM = unique(garden$OM)) data1 = list(seeds = c(seed_data$seeds, rep(NA, times = 40)), biomass = c(seed_data$biomass, seq(1,40,1))) params=list("b1", "b2", "seeds", "alpha") sink("ranmodelgroE.txt") #the sink function drops the code as a text file into your working directory cat(' model{ for(i in 1:length(seeds)) { seeds[i] ~ dnbinom(p[i], r[i]) p[i] <- 1/alpha r[i] <- (b1*(biomass[i]^b2))/(alpha - 1) } b1 ~ dunif(100,300) b2 ~ dunif(1,2) alpha ~ dunif(1, 1000) } ',fill=TRUE) sink() set.seed(101) ran.MvMM10 =jags(data1,inits=NULL,unlist(params),model.file="ranmodelgroE.txt",n.chains=5,n.iter=22000,n.burnin=2000,n.thin= 50) library("R2jags") source("generalBAYESIANcode.r") pars = gipar(ran.MvMM10) seed_preds = pars$seeds[, 25:64] # Note there are 2000 samples from the posterior ## Each column in the matrix represents predictions for a different biomass level x = rep(0, times = 50*40) pred_seeds = matrix(x, nrow = 50, ncol = 40) mean_seeds = rep(0, times = 40) median_seeds = rep(0, times = 40) prob = rep(0, times = 40) for (i in 0:50) { prob[i] = 50 + 38*i for (j in 1:40) { c = sort(seed_preds[,j]) pred_seeds[i,j] = c[prob[i]] mean_seeds[j] = mean(c) median_seeds[j] = median(c) } } biomass = seq(1, 40, 1) pred_contours = data.frame(pred_seeds) pred_contour1 = t(pred_contours) argh = melt(pred_contour1) mass_vals = rep(biomass, times = 50) pred_contours = data.frame(argh, mass_vals) # make sure to check name on Var2 used below contour_plot = ggplot(pred_contours, aes(x = mass_vals)) for (i in 1:50) { pred_contours_1 = subset(pred_contours, Var2 == i) contour_plot = contour_plot + stat_smooth(data = pred_contours_1, aes(y = value), se = FALSE, linetype = "dashed") } fecund_output = contour_plot + geom_point(aes(x = biomass, y = seeds), data = seed_data) fecund_output + theme_bw() + labs(x = "Plant biomass (g)", y = "Seeds/plant")