Skip to content

Commit 496361d

Browse files
committed
first commit
0 parents  commit 496361d

File tree

10 files changed

+480
-0
lines changed

10 files changed

+480
-0
lines changed

.gitignore

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.Rproj.user
2+
.Rhistory
3+
.RData
4+
.Ruserdata
5+
.directory
6+
7+
**/rsconnect
8+
*.html

LICENSE

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
MIT License
3+
4+
Copyright (c) 2016 Eduard Szöcs
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
The above copyright notice and this permission notice shall be included in all
14+
copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
SOFTWARE.

README

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
A collection of some of my Shiny apps.

glm_explorer/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

glm_explorer/exercises.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Exercises
2+
3+
### Gausian Linear Model
4+
#### Data Generation
5+
6+
1. Change only the intercept. What happens to the simulated data
7+
2. Set the intercept back to 0, change only the slope. What happens to the simulated data
8+
3. Set the intercept to 3, change the slope. What happens to the simulated data
9+
4. Set intercept and slope both back to zero. Change only the group difference. What do you observe
10+
5. Set the group difference to 4, change only the slope. What happens to the simulated data
11+
6. Set the group difference to 4, and the slope to 4.
12+
Change only the intercept. What happens to the simulated data
13+
7. Set the intercept to 0, the group difference to 2, the slope to 2.
14+
Change the interaction. What do you observe
15+
8. Set the intercept to 0, the group difference to 2, the slope to 2 and the interaction to 0.
16+
Change sigma.
17+
18+
19+
#### Model fitting
20+
21+
1. Set all to zero. Set the intercept to 1 and the slope to -2.
22+
In the model tab: What is the difference between `intercept' and 'x' as fitted terms
23+
2. Keep the intercept to 1 and the slope to -2. Set the group difference to 3. What is the difference between 'x', 'fac' and 'both' as fitted terms
24+
3. Keep the intercept to 1, the slope to -2 and the group difference to 3. Set the interaction to -5. What is the difference between 'both' and interaction as fited terms
25+
4. Keep all settings. Change sigma. What happens to the Confidence intervals
26+
27+
#### Model Summary and Coefficients
28+
29+
#### Model Diagnostics
30+
31+
32+
33+
### Poisson Linear Model
34+
35+
#### Model fitting
36+
37+
#### Model Summary and Coefficients
38+
39+
#### Model Diagnostics
40+
41+
#### Overdispersion
42+
43+
### Negative Binomial Linear Model
44+
45+
#### Model fitting
46+
47+
#### Model Summary and Coefficients
48+
49+
#### Model Diagnostics

glm_explorer/functions.R

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
library(ggplot2)
2+
library(MASS)
3+
library(ggfortify)
4+
library(gridExtra)
5+
library(markdown)
6+
7+
#' @param n number of observations
8+
#' @param a intercept
9+
#' @param b_x effect of continuous variable
10+
#' @param b_fac effect of categorial variable
11+
#' @param b_int interaction effect
12+
#' @param link link function
13+
#' @param family error distribution function
14+
datagen <- function(n = 100,
15+
a = 0,
16+
b_x = 2,
17+
b_fac = -1,
18+
b_int = -3,
19+
link = c('identity', 'log'),
20+
family = c('gaussian', 'poisson', 'negbin'),
21+
sigma = 1,
22+
dispersion = 4) {
23+
link <- match.arg(link)
24+
family <- match.arg(family)
25+
26+
x <- runif(n)
27+
fac <- sample(c('A', 'B'), n, replace = TRUE)
28+
fac_dummy <- ifelse(fac == 'A', 0, 1)
29+
30+
# mean
31+
link_mu <- a + b_x*x + b_fac*fac_dummy + b_int*fac_dummy*x
32+
mu <- switch(link,
33+
identity = link_mu,
34+
log = exp(link_mu))
35+
if (family %in% c('poisson', 'negbin') && any(mu < 0))
36+
stop("Cannot simulate Poisson or NegBin with negative mean. Maybe change link function.")
37+
# response
38+
y <- switch(family,
39+
poisson = rpois(n, mu),
40+
gaussian = rnorm(n, mean = mu, sd = sigma),
41+
negbin = rnbinom(n, mu = mu, size = 1/dispersion))
42+
43+
# return
44+
df <- data.frame(x, y, fac)
45+
return(df)
46+
}
47+
48+
#' @param df data.frame as returned by datagen
49+
#' @param link link function
50+
#' @param family error distribution function
51+
datamodel <- function(df,
52+
family = c('gaussian', 'poisson', 'negbin'),
53+
link = c('identity', 'log'),
54+
terms = c('intercept', 'x', 'fac', 'both', 'interaction')){
55+
link <- match.arg(link)
56+
family <- match.arg(family)
57+
terms <- match.arg(terms)
58+
form <- switch(terms,
59+
intercept = as.formula(y ~ 1),
60+
x = as.formula(y ~ x),
61+
fac = as.formula(y ~ fac),
62+
both = as.formula(y ~ x+fac),
63+
interaction = as.formula(y ~ x*fac)
64+
)
65+
start <- switch(terms,
66+
intercept = 1,
67+
x = rep(1, 2),
68+
fac = rep(1, 2),
69+
both = rep(1, 3),
70+
interaction = rep(1, 4)
71+
)
72+
73+
mod <- switch(family,
74+
poisson = glm(form, data = df, family = poisson(link = link),
75+
start = start),
76+
gaussian = glm(form, data = df, family = gaussian(link = link),
77+
start = start),
78+
negbin = glm.nb(form, data = df), link = link)
79+
return(mod)
80+
}
81+
82+
#' @param df data.frame as returned by datagen
83+
#' @param mod model as returned by datamodel
84+
dataplot <- function(df, mod = NULL) {
85+
lim <- c(-10, 10)
86+
# model fit + ci
87+
pdat <- expand.grid(x = seq(min(df$x), max(df$x),
88+
length.out = 100),
89+
fac = levels(df$fac))
90+
pdat$fit <- predict(mod, newdata = pdat, type = "link")
91+
pdat$se <- predict(mod, newdata = pdat, type = "link", se.fit = TRUE)$se.fit
92+
mod_fam <- mod$family$family
93+
mod_fam <- ifelse(grepl('Negative Binomial', mod_fam), 'negbin', mod_fam)
94+
crit <- switch(mod_fam,
95+
gaussian = qt(0.975, df = mod$df.residual),
96+
poisson = qnorm(0.975),
97+
negbin = qt(0.975, df = mod$df.residual))
98+
pdat$lwr <- pdat$fit - crit * pdat$se
99+
pdat$upr <- pdat$fit + crit * pdat$se
100+
pdat$fit_r <- mod$family$linkinv(pdat$fit)
101+
pdat$lwr_r <- mod$family$linkinv(pdat$lwr)
102+
pdat$upr_r <- mod$family$linkinv(pdat$upr)
103+
104+
# simulate from model for PI
105+
nsim <- 1000
106+
y_sim <- simulate(mod, nsim = nsim)
107+
y_sim_minmax <- apply(y_sim, 1, quantile, probs = c(0.05, 0.95))
108+
simdat <- data.frame(ysim_min = y_sim_minmax[1, ],
109+
ysim_max = y_sim_minmax[2, ],
110+
x = df$x,
111+
fac = df$fac)
112+
p <- ggplot() +
113+
geom_ribbon(data = simdat, aes(x = x,
114+
ymax = ysim_max, ymin = ysim_min,
115+
fill = fac), alpha = 0.2) +
116+
geom_line(data = pdat, aes(x = x, y = fit_r, col = fac)) +
117+
geom_line(data = pdat, aes(x = x, y = upr_r, col = fac),
118+
linetype = 'dashed') +
119+
geom_line(data = pdat, aes(x = x, y = lwr_r, col = fac),
120+
linetype = 'dashed') +
121+
geom_point(data = df, aes(x = x, y = y, color = fac)) +
122+
labs(y = 'y') +
123+
ylim(lim)
124+
p
125+
}
126+
127+
coefplot <- function(a = 2,
128+
b_x = 1,
129+
b_fac = 1,
130+
b_int = -2,
131+
mod) {
132+
coefs <- coef(mod)
133+
se <- diag(vcov(mod))^0.5
134+
terms <- c('a', 'b_x', 'b_fac', 'b_int')
135+
terms <- terms[seq_along(coefs)]
136+
truths <- c(a, b_x, b_fac, b_int)
137+
truths <- truths[seq_along(coefs)]
138+
df <- data.frame(term = terms, estimate = coefs, se, truths)
139+
mod_fam <- mod$family$family
140+
mod_fam <- ifelse(grepl('Negative Binomial', mod_fam), 'negbin', mod_fam)
141+
crit <- switch(mod_fam,
142+
gaussian = qt(0.975, df = mod$df.residual),
143+
poisson = qnorm(0.975),
144+
negbin = qt(0.975, df = mod$df.residual))
145+
df$lwr <- df$estimate - crit * df$se
146+
df$upr <- df$estimate + crit * df$se
147+
148+
p <- ggplot(df, aes(x = term)) +
149+
geom_pointrange(aes(y = estimate, ymax = upr, ymin = lwr)) +
150+
geom_point(aes(y = truths), col = 'red') +
151+
geom_vline(xintercept = 0, linetype = 'dashed') +
152+
coord_flip()
153+
p
154+
}
155+
156+
diagplot <- function(df, mod) {
157+
rfdat <- data.frame(res = residuals(mod, type = 'pearson'),
158+
fac = df$fac,
159+
fit = predict(mod, type = 'response'))
160+
p1 <- ggplot() +
161+
geom_point(data = rfdat, aes(x = fit, y = res, color = fac)) +
162+
ggtitle('Residuals vs. Fitted') +
163+
labs(x = 'Residuals', y = 'Fitted') +
164+
geom_smooth(data = rfdat, aes(x = fit, y = res, color = fac),
165+
se = FALSE) +
166+
geom_smooth(data = rfdat, aes(x = fit, y = res), color = 'blue',
167+
se = FALSE) +
168+
geom_abline(aes(intercept = 0, slope = 0), linetype = 'dashed')
169+
170+
171+
ofdat <- data.frame(obs = df$y,
172+
fac = df$fac,
173+
fit = predict(mod, type = 'response'))
174+
p2 <- ggplot() +
175+
geom_point(data = ofdat, aes(x = obs, y = fit, color = fac)) +
176+
ggtitle('Fitted vs Observed') +
177+
labs(x = 'Observed', y = 'Fitted') +
178+
geom_abline(aes(intercept = 0, slope = 1), linetype = 'dashed')
179+
plot.list <- list(p1, p2)
180+
new("ggmultiplot", plots = plot.list, nrow = 1, ncol = 2)
181+
}
182+
183+
184+
chk_pos <- function(y, fam) {
185+
if (fam %in% c('poisson', 'negbin') && any(y < 0)) {
186+
"Negative values in data. Cannot fit Poisson or NegBin."
187+
} else {
188+
NULL
189+
}
190+
}

glm_explorer/introduction.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
## Introduction

glm_explorer/server.R

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
2+
# This is the server logic for a Shiny web application.
3+
# You can find out more about building applications with Shiny here:
4+
#
5+
# http://shiny.rstudio.com
6+
#
7+
8+
library(shiny)
9+
source('functions.R')
10+
11+
12+
shinyServer(function(input, output) {
13+
df <- reactive({
14+
datagen(n = input$n,
15+
a = input$a,
16+
b_x = input$b_x,
17+
b_fac = input$b_fac,
18+
b_int = input$b_int,
19+
link = input$link,
20+
family = input$family,
21+
sigma = input$sigma,
22+
dispersion = input$dispersion)
23+
})
24+
25+
mod <- reactive({
26+
validate(
27+
chk_pos(df()$y, input$family_mod)
28+
)
29+
30+
datamodel(df(),
31+
family = input$family_mod,
32+
link = input$link_mod,
33+
terms = input$terms_mod)
34+
})
35+
36+
output$Plot_raw <- renderPlot({
37+
dat <- df()
38+
dataplot(dat)
39+
})
40+
41+
output$Plot_model <- renderPlot({
42+
dataplot(df(), mod())
43+
})
44+
45+
output$Plot_model2 <- renderPlot({
46+
dataplot(df(), mod())
47+
})
48+
49+
output$Summary <- renderPrint({
50+
summary(mod())
51+
})
52+
53+
output$Plot_coefs <- renderPlot({
54+
coefplot(a = input$a,
55+
b_x = input$b_x,
56+
b_fac = input$b_fac,
57+
b_int = input$b_int,
58+
mod = mod())
59+
})
60+
61+
output$Plot_diag <- renderPlot({
62+
diagplot(df(), mod())
63+
})
64+
})

glm_explorer/shiny.Rproj

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Version: 1.0
2+
3+
RestoreWorkspace: Default
4+
SaveWorkspace: Default
5+
AlwaysSaveHistory: Default
6+
7+
EnableCodeIndexing: Yes
8+
UseSpacesForTab: Yes
9+
NumSpacesForTab: 2
10+
Encoding: UTF-8
11+
12+
RnwWeave: knitr
13+
LaTeX: pdfLaTeX
14+
15+
AutoAppendNewline: Yes

0 commit comments

Comments
 (0)