Debian Codegraph @

inst/examples/olympics.brew

raw
1 % Rapporter Development Team
2 % Predictions about Olympics
3 % 2012
4
5 <%=
6 ## ---------------------------------------------------------------
7 ##
8 ## INTRODUCTION
9 ## ============
10 ##
11 ## This brew file is a POC demo of integrating `pander` in web
12 ## applications. Online demo available at:
13 ##
14 ## http://demo.rapporter.net
15 ##
16 ## MANUAL USAGE
17 ## ============
18 ##
19 ## Set `u` and `weight` parameter before running this `brew` file!
20 ##
21 ## Example
22 ## -------
23 ##
24 ## u <- "ATH-220"
25 ## weight <- TRUE
26 ##
27 ## ---------------------------------------------------------------
28
29 ## loading required packages
30 suppressPackageStartupMessages(library(XML))
31 suppressWarnings(suppressPackageStartupMessages(library(ggplot2)))
32 suppressPackageStartupMessages(library(gvlma))
33
34 ## set options
35 eO <- evalsOptions()
36 pO <- panderOptions()
37 evalsOptions('width', 800)
38 evalsOptions('height', 600)
39 evalsOptions('graph.unify', TRUE)
40 panderOptions('table.split.table', Inf)
41 panderOptions('graph.symbol', 19)
42 panderOptions('graph.legend.position', 'top')
43 if (grepl("w|W", .Platform$OS.type))
44 windowsFonts("Trebuchet MS" = windowsFont("Trebuchet MS"))
45 panderOptions('graph.fontfamily', "Trebuchet MS")
46 panderOptions('graph.background', 'transparent')
47
48 #' Pretty time printing
49 #' @param sec integer
50 #' @param transform if set to FALSE the input will be returned without any tweaks
51 #' @return character in \code{hours:minutes:seconds} format
52 ms <- function(sec, transform = TRUE) {
53 sapply(sec, function(sec) {
54 if (is.na(sec))
55 return(NA)
56 if (transform) {
57 if (sec < 60) {
58 msec <- sec %% 1
59 if (msec == 0)
60 msec <- ''
61 else
62 msec <- paste0('.', round(msec, 2) * 100)
63 } else
64 msec <- ''
65 sec <- round(sec)
66 minute <- sec %/% 60
67 if (minute > 59) {
68 sec <- sprintf("%02d", sec - minute * 60)
69 hours <- minute %/% 60
70 minute <- sprintf("%02d", minute - hours * 60)
71 paste0(paste(hours, minute, sec, sep=":"), msec)
72 } else {
73 sec <- sprintf("%02d", sec - minute * 60)
74 paste0(paste(minute, sec, sep=":"), msec)
75 }
76 } else
77 round(sec, 2)
78 })
79 }
80
81 #' Revert pretty time printing
82 #' @param text character in \code{hours:minutes:seconds} format
83 #' @param transform if set to FALSE the input will be returned without any tweaks
84 #' @return numeric
85 rms <- function(text, transform = TRUE) {
86 sapply(text, function(x) {
87 if (transform) {
88 x <- as.numeric(strsplit(x, ':')[[1]])
89 if (length(x) == 1)
90 return(x)
91 if (length(x) == 2)
92 return(x[1] * 60 + x[2])
93 if (length(x) == 3)
94 return(x[1] * 60^2 + x[2] * 60 + x[3])
95 } else
96 round(as.numeric(x), 2)
97 }, USE.NAMES = FALSE)
98 }
99
100 #' Plot predictions
101 #' @param df a data frame with Year, Result columns
102 #' @param models predefined models' names to plot
103 plotPredictions <- function(df, models) {
104
105 ## custom options
106 panderOptions('graph.fontfamily', "Trebuchet MS")
107
108 ## custom variables - satisfying our DRY needs
109 Y <- df[, 'Year']
110 Y2012 <- c(Y, 2012)
111 R <- df[, 'Result']
112 allvalues <- unlist(c(R, mget(paste0(models, '.predict'), envir = parent.frame())))
113 ff <- panderOptions('graph.fontfamily')
114 fc <- panderOptions('graph.fontcolor')
115 gc <- panderOptions('graph.colors')
116 gt <- panderOptions('graph.grid.lty')
117 gcc <- panderOptions('graph.grid.color')
118 mn <- mget(paste0(models, '.name'), envir = parent.frame())
119
120 ## custom par settings
121 par(
122 family = ff,
123 lwd = 2,
124 pch = panderOptions('graph.symbol'),
125 col.axis = fc, col.lab = fc, col.main = fc, col.sub = fc,
126 mar = c(3,4,3,3), family = ff, font = 4)
127
128 ## results
129 plot(Y, R, ylim = c(min(allvalues), max(allvalues)), xlim = c(min(Y), 2012), xaxt = "n", yaxt= "n", xlab = "", ylab = "", cex.lab = 2, cex.main = 2, cex.axis = 2, cex = 2, pch = 16, bg = "transparent", family = ff, font = 4)
130
131 ## title
132 mtext(paste0("Our predictions for the ", df$Event[1]), line = 1, side = 3, family = ff, cex=2, font=4, col ='black')
133
134 ## get y axis's ticks
135 ylime <- trunc(c(min(R), max(R)))
136 yperiod <- trunc(diff(ylime)/5)
137 if (diff(ylime) < 5) {
138 ylime <- round(c(max(R), min(R)), 2)
139 yperiod <- round(diff(ylime) / 5, 2)
140 }
141 ylime <- c(ylime[1], ylime[1] + 1:5 * yperiod)
142
143 ## draw x axis
144 axis(1, at = Y2012, Y2012, cex = 2, family = ff, font=4)
145 for (y in Y2012)
146 abline(v = y, lty = gt, col = gcc, lwd = 0.5)
147
148 ## draw y axis
149 par(las = 1, family = ff)
150 axis(2, at = ylime, ms(ylime, resultInTime), cex = 2, family = ff, font=4)
151 for (y in ylime)
152 abline(h = y, lty = gt, col = gcc, lwd = 0.5)
153
154 points(Y, R)
155
156 ## plotting models' lines & text
157 for (m in models) {
158 lines(Y2012, get(paste0(m, '.predict')), col = gc[which(m == models)])
159 lines(Y2012, get(paste0(m, '.predict')), lwd = get(paste0(m, '.width')), col = paste0(gc[which(m == models)], '44'))
160 points(2012, tail(get(paste0(m, '.predict')), 1), pch = 19, col = gc[which(m == models)], cex = 3.5)
161 yy <- tail(get(paste0(m, '.predict')), 1)
162 ys <- ms(yy, resultInTime)
163 xx <- 2012 - strwidth(ys, cex = 1.5)
164 text(xx, yy, ys, col = gc[which(m == models)], cex = 1.5)
165 }
166
167 ## add a custom legend
168 l.pos <- ifelse(yy < mean(R), 'topright', 'bottomright')
169 mnames <- unlist(mget(paste0(models, '.name'), envir = parent.frame()), use.names = FALSE)
170 legend(l.pos, mnames, lty = rep(1, times = length(models)), pch = rep(19, times = length(models)), col = rep(gc[1:length(models)], times = 2), adj = c(0, .6), cex = 2, text.col = 'black', text.width = strwidth(paste(mnames, collapse = ' ')) * 1.1)
171 }
172 %>
173
174 <%=
175 ## datafile store
176 dir.create(file.path(getwd(), 'reports', 'data'), recursive = TRUE, showWarnings = FALSE)
177 datafile <- file.path(getwd(), 'reports', 'data', u)
178
179 ## url should be set before calling this `brew` file in a format like: `SWI-240`
180 uri <- strsplit(u, '-', fixed = TRUE)[[1]]
181 url <- paste0('http://www.databaseolympics.com/sport/sportevent.htm?sp=', uri[1], '&enum=', uri[2])
182
183 ## fetching data from \url{databaseolympics.com} if not cached
184 if (!file.exists(datafile)) {
185 d <- readHTMLTable(readLines(url, warn = FALSE), which = 2, header = TRUE)
186 saveRDS(d, file = datafile)
187 } else {
188 d <- readRDS(datafile)
189 }
190 %>
191
192 <%=
193 ## defining events which seem to be invalid
194 dEvents <- tail(as.character(d$Event[d$Event != '']), 1)
195 dEvents.invalid <- which(d$Event != dEvents)
196 %>
197
198 <%
199 if (exists('d')) {
200 %>
201
202 ## Welcome!
203
204 You have selected **<%=dEvents %>** in this demo without any additional parameters, so we try to guess what are you up to. Let us fit some statistical models on previous results in **<%=dEvents %>** and try to predict the results in 2012 *if we assume* that the performance of the winners, so the forthcoming results also fit the historical data.
205
206 ### Historical data
207
208 We have fetched some data from [databaseolympics.com](<%=url%>):
209
210 <%=d%>
211
212 <%=
213 ## removing events which seem to be invalid
214 if (length(dEvents.invalid) > 0)
215 d <- d[-dEvents.invalid, ]
216
217 ## just dealing with the winners ATM
218 golddata <- subset(d, Medal %in% "GOLD")
219
220 ## removing duplicated rows (we just need the Results)
221 if (any(table(golddata['Year']) > 1))
222 golddata <- golddata[-which(duplicated(golddata['Year'])), ]
223
224 ## are we dealing with time results?
225 resultInTime <- any(grepl(':', golddata$Result))
226
227 ## transforming data
228 d$Event <- as.character(d$Event)
229 golddata$Year <- as.numeric(as.character(golddata$Year))
230 years <- c(as.numeric(as.character(sort(unique(golddata$Year)))), 2012)
231 golddata$Result <- rms(as.character(golddata$Result), resultInTime)
232 rownames(golddata) <- NULL
233 %>
234
235 And applied some filters and data transformation on the above database to let us create a data set ready for the below analysis:
236
237 <%=
238 if (weight)
239 golddata$weight <- (golddata$Year - min(golddata$Year) + 4) / sum(golddata$Year - min(golddata$Year) + 4) * length(golddata$Year)
240 golddata
241 %>
242
243 <%
244 if (nrow(golddata) > 5) {
245 %>
246
247 We do not even need all columns of this table, we will deal only with *Year* and the *Result* below which is eligible to build some simple statistical models to predict the expected results in 2012.
248
249 Please note that the below estimates are not based on any causal model, nor we claim it could be accomplished. We just demonstrate: these numbers can be expected leaning solely on prior Olympic records.
250
251 <%=
252 ## fitting a non-linear model
253 if (weight) {
254 nonLin <- suppressWarnings(lm(Result ~ poly(Year, 4), weights = weight, data = golddata))
255 } else {
256 nonLin <- suppressWarnings(lm(Result ~ poly(Year, 4), data = golddata))
257 }
258 nonLin.name <- 'power prediction'
259 nonLin.predict <- suppressWarnings(predict(nonLin, newdata = data.frame(Year = years)))
260 nonLin.width <- (100 - ((1 - mean(summary(nonLin)$coefficients[, "Pr(>|t|)"]))^2 * 100)) + (1 - summary(nonLin)$adj.r.squared) * 100
261 golddata2012 <- rbind(golddata, c(2012, rep(NA, times = ncol(golddata)-1)))
262 golddata2012$nonLin <- nonLin.predict
263 names(nonLin$coefficients )[1:5] <- c('Intercept', 'Year', 'Year^2', 'Year^3', 'Year^4')
264
265 ## fitting a log-linear model
266 if (weight) {
267 logLin <- lm(log(Result) ~ Year, weights = weight, data = golddata)
268 } else {
269 logLin <- lm(log(Result) ~ Year, data = golddata)
270 }
271 logLin.name <- 'simple prediction'
272 logLin.predict <- exp(predict(logLin, newdata = data.frame(Year = years)))
273 logLin.width <- (100 - ((1 - mean(summary(logLin)$coefficients[, "Pr(>|t|)"]))^2 * 100)) + (1 - summary(logLin)$adj.r.squared) * 100
274 golddata2012$logLin <- logLin.predict
275 %>
276
277 ### Visualized models and predictions
278
279 We have built two different models: a log-linear (*simple*) and a non-linear (*power*) one. Weights were <%=ifelse(weight, '', 'not')%> applied.
280
281 Both models on a complex plot build with `base` R (actually with `graphics` functions):
282
283 <%=
284 ## saving options as tweaking some internals
285 evalsOptions('graph.unify', FALSE)
286 %><%=
287 ## plotting
288 models <- c('nonLin', 'logLin')
289 plotPredictions(golddata, models)
290 %><%=
291 ## reset graph unify option
292 evalsOptions('graph.unify', TRUE)
293 %>
294
295 Another quick plot themed by our [back-end](http://daroczig.github.com/pander/) building on `ggplot2`:
296
297 <%=
298 g <- ggplot(golddata2012) + geom_point(aes(x=Year, y=Result)) + geom_smooth(aes(x=Year, y=nonLin), alpha=0.2) + geom_smooth(aes(x=Year, y=logLin, col = "#56B4E9"), alpha=0.2, col = "#009E73") + ggtitle(d$Event[1]) + ylab("") + xlab("") + theme_bw() + theme(legend.position = "none")
299 if (resultInTime)
300 g <- g + scale_y_continuous(labels = ms)
301 g
302 %>
303
304 ## The models in more details
305
306 ### Non-linear model
307
308 Fitting a non-linear model on the winning times cannot be easier from a client's point of view with Rapporter:
309
310 <%=
311 ## printing
312 nonLin
313 %>
314
315 #### Validations of the Model Assumptions
316
317 And checking the assumptions of the fitted model could be also useful: <%=
318 a <- summary(gvlma(nonLin))
319 ifelse(any(a$Decision == 'Assumptions NOT satisfied!'), 'it seems that some assumptions of the model was *not* satisfied!', 'all the assumptions of the model were satisfied!')
320 %>
321
322 In details:
323
324 <%=
325 pandoc.table.return(a, split.tables = Inf)
326 %>
327
328 #### Diagnostic plots
329
330 Professional users might find the diagnostic plots of R helpful too. Here you can find a default plot with Rapporter's automatically applied theme:
331
332 <%=
333 par(mfrow = c(2, 2))
334 +suppressWarnings(plot(nonLin))
335 %>
336
337 But back to the model: the adjusted R-squared equals to <%=summary(nonLin)$adj.r.squared%> with a p-value of <%=round(anova(nonLin)$'Pr(>F)'[1], 5)%>.
338
339 <%=anova(nonLin)%>
340
341 ### Log-linear model
342
343 And our log-linear model looks like:
344
345 <%=
346 ## printing
347 logLin
348 %>
349
350 #### Validations of the Model Assumptions
351
352 Where <%=
353 a <- summary(gvlma(logLin))
354 ifelse(any(a$Decision == 'Assumptions NOT satisfied!'), 'some assumptions were *not* satisfied:', 'the assumptions were satisfied:')
355 %>
356
357 <%=
358 pandoc.table.return(a, split.tables = Inf)
359 %>
360
361 #### Diagnostic plots
362
363 And the diagnostic plots again:
364
365 <%=
366 par(mfrow = c(2, 2))
367 +suppressWarnings(plot(logLin))
368 %>
369
370 Where the adjusted R-squared equals to <%=summary(logLin)$adj.r.squared%> with a p-value of <%=round(anova(logLin)$'Pr(>F)'[1], 5)%>.
371
372 <%=anova(logLin)%>
373
374 #### We really hope that you like this short demo, please do not forget to [sign up for our forthcoming next-generation web application](http://rapporter.net) to create your own report!
375
376 ## Bye!
377
378 <% } else { %>
379
380 We are really sorry, but we cannot build a model from only *<%=nrow(golddata)%>* result<%=ifelse(nrow(golddata) > 1, 's', '')%> at the Olympics.
381
382 **Please try another sport event!**
383
384 <% } %>
385
386 <% } else { %>
387
388 ### ERROR
389
390 `Database not found.`
391
392 Please try again later and report this issue at [email protected].
393
394 <% } %>
395
396 <%=
397 ## resetting options
398 for (o in names(eO))
399 evalsOptions(o, eO[[o]])
400 for (o in names(pO))
401 panderOptions(o, pO[[o]])
402 %>