#Hierarchical model for forecasting the outcomes of binary referenda #Supplementary R Code #Used for foreasting the outcome of the EU membership referendum and Scottish referendum (requires uncommenting several inputs) library(rjags) ###########DATA PREPARATION############# #reading in data d d=read.csv("refEU.csv") #EU referendum #d=read.csv("refSC.csv") #Scottish referendum #function for rounding data round2 = function(x, n) { posneg = sign(x) z = abs(x)*10^n z = z + 0.5 z = trunc(z) z = z/10^n z*posneg } #data cleaning and preparation #sample size ss=d$Sample #opinion polls outcome s2=matrix(round2(unlist(d[,1:3])/100*ss,0),dim(d)[1],3) #ensuring the outcomes sum up to sample size s2[,3]=ss-apply(s2[,1:2],1,sum) #unique days of polling before the referendum used to create time function tu=unique(d$day) #indicator of a day the poll took place indi=cumsum(!duplicated(d$day)) indj=unlist(sapply(as.vector(table(d$day)),seq_len)) #time trend linear tu1=tu/sd(tu) #time trend quadratic tu1=cbind(tu1,tu^2/sd(tu^2)) #time trend cubic tu1=cbind(tu1,tu^3/sd(tu^3)) #### indices for splines #count_day_polls=as.vector(table(d$day)) #function creating splines for a given length of data #length of data = ind-1 #pos_ind denotes a position in the vector of various lengths #knts - vector of positions of knots ind.bs.wrap=function(ind,pos_ind,knts){ #creates b-splines for a given length of the data ind_bs=matrix(0,ind[pos_ind],length(knts)+4) knots_ind=knts[knts