-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.Rhistory
512 lines (512 loc) · 23.2 KB
/
.Rhistory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
h = exp( b)
lengths <- c(breaks, maxDuration) - c(1, breaks)
H = cumsum( lengths*h)
S = exp(-H)
output <- list(S, PWC)
return(output)
}
plotPWC <- function(breaks, S, maxDuration, subset){
xgrid <- c(1,breaks, maxDuration) #returns the cut points
ygrid <- S #returns the corresponding hazards
graph <- data.frame(x = seq(1, maxDuration, by = 0.1))
for(i in 1:length(graph$x)){
for(j in 2:length(xgrid)){
if(graph$x[i] < xgrid[j] & graph$x[i] >= xgrid[j-1]){
graph$y[i] <- ygrid[[j-1]]
}
}
}
p <- ggplot(graph[ graph$x < subset, ]) +
geom_line(aes(x = x, y = y)) +
xlab("duration") +
ylab("survival")
return(p)
}
breaks1 <- c(2, 5, 10, 20, 50, 500)
breaks2 <- c(2, 3,4,5, 8, 16, 32, 64, 128, 256, 512)
controls <- c("gender", "urban", 'public',"catholic", "protest", "special")
S1 <- PWC(breaks1, df)[[1]]
plotPWC(breaks1, S1, maxDuration, subset = 50)
# Setup code - loading the data or packages
rm(list=ls())
variables <- c("gender", "marstat", "contract", "schooltype", "urban", "birthyr", "classize")
# packages ---------------------------------------------------------------------
library(stargazer)
library(survival)
library(haven)
#library(xtable)
#library(RCT)
library(foreign)
library(tidyverse)
library(ggfortify)
library(survminer)
library(splines2)
library(casebase)
# for plodurationing the smooth hazard rate
library(visreg)
# for computing piecewise constant hazard rates
library(pch)
#for unobserved heterogeneity models
library(parfm)
# for computing the cumulative hazards
library(zoo)
# reading in data --------------------------------------------------------------
dat <- "C:\\Users\\kiera\\OneDrive\\Documents\\Tinbergen MPhil\\Applied Microeconometrics\\Applied_micro"
setwd(dat)
df <- as.data.frame(read_dta("FlowSpells.dta"), stringsAsFactors=F)
df <- df[df[["sptype"]] == 2, ] #only focus on the sickness periods
# Hazard and survival functions ------------------------------------------------
hazard <- function(df, duration, censored, t){
numerator <- sum((1-df[[censored]])*ifelse(t < df[[duration]] & df[[duration]] <= t + 1, 1, 0))
denominator <- ifelse(any(df[[duration]] > t), sum(df[[duration]] > t), 1) #can't divide by zero
return(numerator/denominator)
}
survival <- function(survivalTable, t){
return(ifelse(t > 1, prod(1 - survivalTable$hazard[1:(t-1)]), 1))
}
# Question 1 -------------------------------------------------------------------
# functions ---------------------------------------------------------------------
# functions that compute the hazard and survival functions
hazard <- function(df, duration, censored, t){
# computing the numerator in a vectorised way
numerator <- sum((1-df[[censored]])*ifelse(t < df[[duration]] & df[[duration]] <= t + 1, 1, 0))
denominator <- ifelse(any(df[[duration]] > t), sum(df[[duration]] > t), 1)
return(numerator/denominator)
}
survival <- function(survivalTable, t){
# this uses that the survival function is the complement of the cumulative
# hazard
return(ifelse(t > 1, prod(1 - survivalTable$hazard[1:(t-1)]), 1))
}
# function to compute the survival table from the dataset
survTableGen <- function(df, col = FALSE, grp = FALSE){
duration <- 1:max(df$splength)
survivalTable <- data.frame(duration)
if(col == FALSE){ #if no column specified, select all data
survivalTable$hazard <- sapply(duration, hazard, df = df,
duration = "splength", censored = "rcensor")
survivalTable$survival <- sapply(duration, survival, survivalTable = survivalTable)
} else { #if column specified, only select data from the selected group
subset <- df[df[[col]]==grp,]
survivalTable$hazard <- sapply(duration, hazard, df = subset,
duration = "splength", censored = "rcensor")
survivalTable$survival <- sapply(duration, survival, survivalTable = survivalTable)
survivalTable[[col]] <- grp
}
return(survivalTable)
}
# function that computes hazard rates and survival function by groups defined
# by continuous variables
sur_haz_grp <- function(col, df){
groups <- unique(df[[col]])
out_dfs <- lapply(groups, survTableGen, col = col, df = df)
out_df_merged <- bind_rows(out_dfs)
hazard <- ggplot(out_df_merged, aes(x =duration, y=hazard, colour = as.factor(get(col)))) +
geom_line() +
theme(legend.title=element_blank())
survival <- ggplot(out_df_merged, aes(x =duration, y=survival, colour = as.factor(get(col)))) +
geom_line() +
theme(legend.title=element_blank())
# finally testing for difference between the survival rates
return(list(hazard, survival))
}
# running code ----------------------------------------------------------------
survivalTable <- survTableGen(df)
ggplot(data = survivalTable, mapping = aes(x =duration, y= hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable, mapping = aes(x =duration, y=survival)) +
geom_line()
# now lets do plots for the first two weeks, and the first year
ggplot(data = survivalTable[survivalTable[["duration"]]<=14,], mapping = aes(x =duration, y=hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable[survivalTable[["duration"]]<=14,], mapping = aes(x =duration, y=survival)) +
geom_line()
ggplot(data = survivalTable[survivalTable[["duration"]]<=365,], mapping = aes(x =duration, y=hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable[survivalTable[["duration"]]<=365,], mapping = aes(x =duration, y=survival)) +
geom_line()
# now lets partition by different columns and compute the hazard rates
# partitions: type of school, gender, urbanisation
df[["school_type"]] <- NA
df[["school_type"]][df[["public"]]==1] <- "Public"
df[["school_type"]][df[["catholic"]]==1] <- "Catholic"
df[["school_type"]][df[["protest"]]==1] <- "Protestant"
df[["school_type"]][df[["special"]]==1] <- "Special"
df[["area_type"]] <- NA
df[["area_type"]][df[["urban"]]==1] <- "Urban_1"
df[["area_type"]][df[["urban"]]==2] <- "Urban_2"
df[["area_type"]][df[["urban"]]==3] <- "Urban_3"
df[["area_type"]][df[["urban"]]==4] <- "Urban_4"
df[["area_type"]][df[["urban"]]==5] <- "Urban_5"
df[["gender"]] <- ifelse(df[["gender"]] == 1, "male", "female")
#choose to cut off at 300 because from there the pictures are uninformative
sur_haz_grp("gender", df[df[["splength"]] < 300, ])
sur_haz_grp("area_type", df[df[["splength"]] < 300, ])
sur_haz_grp("school_type", df[!is.na(df[["school_type"]]) & df[["splength"]] < 300, ])
# finally lets test for a difference between the survival rates
survdiff(Surv(splength, rcensor) ~ gender, data=df)
survdiff(Surv(splength, rcensor) ~ urban, data=df)
survdiff(Surv(splength, rcensor) ~ school_type, data=df)
# Question 2 - parametric survival models --------------------------------------
# simple weibull and exponential models
# In order to use the package, we have to make a status indicator
df$status <- ifelse(df$rcensor == 1, 0, 1)
exp_mod <- survreg(Surv(splength, status) ~ public, data=df, dist="exponential")
summary(exp_mod)
weib_mod <- survreg(Surv(splength, status) ~ public, data=df, dist="weibull")
summary(weib_mod)
paste("The scale parameter alpha is: ", 1/weib_mod$scale)
#Note the scale parameter should be intepreted as 1/(rweibull shape)
#The rweibull function is: https://en.wikipedia.org/wiki/Weibull_distribution
#There, we have shape parameter k, which corresponds to our alpha.
#In the example above, the scale is 1.64, so k = 1/1.64
#Thus, k < 1, i.e. decreasing hazard over time (which makes sense)
# now we add some more regressors
weib_mod_2 <- survreg(Surv(splength, status) ~ gender+ public, data=df, dist="weibull")
print(1/weib_mod_2$scale) #no change
summary(weib_mod_2) #negative effect of being male on sickness, public insignificant
weib_mod_3 <- survreg(Surv(splength, status) ~ gender + urban + public,
data=df, dist="weibull")
print(1/weib_mod_3$scale) #again no difference
summary(weib_mod_3) #effect of male still the same, urban/public is insignificant
weib_mod_4 <- survreg(Surv(splength, status) ~ gender + urban + public + catholic +
protest + special, data=df, dist="weibull")
summary(weib_mod_4) #only male and special schools differ a lot in duration
print(1/weib_mod_3$scale) #still no change
# now lets plot the models separately by gender and see if the parameters are
# significantly different using the log-rank test
weib_mod_gen_1 <- survreg(Surv(splength, status) ~ urban + public + catholic +
protest + special, data=df[df[["gender"]]=="male",], dist="weibull")
summary(weib_mod_gen_1)
weib_mod_gen_1$scale
weib_mod_gen_2 <- survreg(Surv(splength, status) ~ urban + public + catholic +
protest + special, data=df[df[["gender"]]== "female",], dist="weibull")
summary(weib_mod_gen_2)
#weib_diff <- survdiff(Surv(splength, status) ~ gender, data=df, dist="weibull")
#I am not really sure how to test difference between the two,
#but I think just looking at the different scale values already gives us
#a reason why to prefer the gender-separate models
#We also look at 'special', because these seem to have different sickness behaviour as well
#
weib_mod_special_1 <- survreg(Surv(splength, status) ~ urban+gender, data=df[df[["special"]]=="1",], dist="weibull")
summary(weib_mod_special_1)
print(1/weib_mod_special_1$scale)
weib_mod_special_2 <- survreg(Surv(splength, status) ~ urban + gender, data=df[df[["special"]]=="0",], dist="weibull")
print(1/weib_mod_special_2$scale)
#indeed, their shape parameters are far apart
# Code for question 3
# Question 3 - piecewise constant ----------------------------------------------
#We follow: https://data.princeton.edu/wws509/r/recidivism
# Fitting piece-wise linear models
#PWC <- function(breaks, df, controls = NULL){
#splitted <- survSplit(Surv(splength, status) ~ ., data = df,
#cut = breaks, episode = "interval", start = "start")
#splitted <- mutate(splitted, exposure = splength - start,
#interval = factor(interval,
#labels = paste("(", c(1,breaks), ",",
#c(breaks,998), "]", sep=""))) %>%
#rename(events = status)
#if(is.null(controls)){
#PWC <- glm(events ~ interval + offset(log(exposure)), data=splitted, family=poisson)
#} else {
#dep_vars <- paste(c("interval", "offset(log(exposure))", controls), collapse="+")
#formula_string <- as.formula(paste("events", dep_vars, sep="~"))
#PWC <- glm(formula_string, data=splitted, family=poisson)
#}
#maxDuration <- max(df[["splength"]])
#b = coef(PWC)[1: length(unique(splitted$interval))]
#h = exp( b)
#lengths <- c(breaks, maxDuration) - c(1, breaks)
#H = cumsum( lengths*h)
#S = exp(-H)
#output <- list(S, PWC)
#return(output)
#}
#plotPWC <- function(breaks, S, maxDuration, subset){
#xgrid <- c(1,breaks, maxDuration) #returns the cut points
#ygrid <- S #returns the corresponding hazards
#graph <- data.frame(x = seq(1, maxDuration, by = 0.1))
#for(i in 1:length(graph$x)){
#for(j in 2:length(xgrid)){
#if(graph$x[i] < xgrid[j] & graph$x[i] >= xgrid[j-1]){
#graph$y[i] <- ygrid[[j-1]]
#}
#}
#}
#p <- ggplot(graph[ graph$x < subset, ]) +
#geom_line(aes(x = x, y = y)) +
#xlab("duration") +
#ylab("survival")
#return(p)
#}
#breaks1 <- c(2, 5, 10, 20, 50, 500)
#breaks2 <- c(2, 3,4,5, 8, 16, 32, 64, 128, 256, 512)
#controls <- c("gender", "urban", 'public',"catholic", "protest", "special")
#S1 <- PWC(breaks1, df)[[1]]
#plotPWC(breaks1, S1, maxDuration, subset = 50)
#S2 <- PWC(breaks2, df)[[1]]
#plotPWC(breaks2, S2, maxDuration, subset = 50)
#S3 <- PWC(breaks2, df, controls)[[2]]
#summary(S3) #once again, only Males and Special have significant signs, but now reversed!
# breaks3 <- c(0, 1,2,3,4,5, 10, 15, 20, 50, 100, 500, 998)
# S4 <- pchreg(Surv(splength, status) ~ gender + urban + public + catholic +
# protest + special, breaks3, data = df)
# S4$beta
# Previous code - piecewise constant ----------------------------------------------
piece_mod_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 4, data=df)
summary(piece_mod_1)
piece_mod_2 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df)
summary(piece_mod_2)
piece_mod_gen_1 <- pchreg(Surv(splength, rcensor) ~ gender, breaks = 20, data=df[df[["gender"]]==1,])
# Setup code - loading the data or packages
rm(list=ls())
variables <- c("gender", "marstat", "contract", "schooltype", "urban", "birthyr", "classize")
# packages ---------------------------------------------------------------------
library(stargazer)
library(survival)
library(haven)
#library(xtable)
#library(RCT)
library(foreign)
library(tidyverse)
library(ggfortify)
library(survminer)
library(splines2)
library(casebase)
# for plodurationing the smooth hazard rate
library(visreg)
# for computing piecewise constant hazard rates
library(pch)
#for unobserved heterogeneity models
library(parfm)
# for computing the cumulative hazards
library(zoo)
# reading in data --------------------------------------------------------------
dat <- "C:\\Users\\kiera\\OneDrive\\Documents\\Tinbergen MPhil\\Applied Microeconometrics\\Applied_micro"
setwd(dat)
df <- as.data.frame(read_dta("FlowSpells.dta"), stringsAsFactors=F)
df <- df[df[["sptype"]] == 2, ] #only focus on the sickness periods
# Hazard and survival functions ------------------------------------------------
hazard <- function(df, duration, censored, t){
numerator <- sum((1-df[[censored]])*ifelse(t < df[[duration]] & df[[duration]] <= t + 1, 1, 0))
denominator <- ifelse(any(df[[duration]] > t), sum(df[[duration]] > t), 1) #can't divide by zero
return(numerator/denominator)
}
survival <- function(survivalTable, t){
return(ifelse(t > 1, prod(1 - survivalTable$hazard[1:(t-1)]), 1))
}
# Question 1 -------------------------------------------------------------------
# functions ---------------------------------------------------------------------
# functions that compute the hazard and survival functions
hazard <- function(df, duration, censored, t){
# computing the numerator in a vectorised way
numerator <- sum((1-df[[censored]])*ifelse(t < df[[duration]] & df[[duration]] <= t + 1, 1, 0))
denominator <- ifelse(any(df[[duration]] > t), sum(df[[duration]] > t), 1)
return(numerator/denominator)
}
survival <- function(survivalTable, t){
# this uses that the survival function is the complement of the cumulative
# hazard
return(ifelse(t > 1, prod(1 - survivalTable$hazard[1:(t-1)]), 1))
}
# function to compute the survival table from the dataset
survTableGen <- function(df, col = FALSE, grp = FALSE){
duration <- 1:max(df$splength)
survivalTable <- data.frame(duration)
if(col == FALSE){ #if no column specified, select all data
survivalTable$hazard <- sapply(duration, hazard, df = df,
duration = "splength", censored = "rcensor")
survivalTable$survival <- sapply(duration, survival, survivalTable = survivalTable)
} else { #if column specified, only select data from the selected group
subset <- df[df[[col]]==grp,]
survivalTable$hazard <- sapply(duration, hazard, df = subset,
duration = "splength", censored = "rcensor")
survivalTable$survival <- sapply(duration, survival, survivalTable = survivalTable)
survivalTable[[col]] <- grp
}
return(survivalTable)
}
# function that computes hazard rates and survival function by groups defined
# by continuous variables
sur_haz_grp <- function(col, df){
groups <- unique(df[[col]])
out_dfs <- lapply(groups, survTableGen, col = col, df = df)
out_df_merged <- bind_rows(out_dfs)
hazard <- ggplot(out_df_merged, aes(x =duration, y=hazard, colour = as.factor(get(col)))) +
geom_line() +
theme(legend.title=element_blank())
survival <- ggplot(out_df_merged, aes(x =duration, y=survival, colour = as.factor(get(col)))) +
geom_line() +
theme(legend.title=element_blank())
# finally testing for difference between the survival rates
return(list(hazard, survival))
}
# running code ----------------------------------------------------------------
survivalTable <- survTableGen(df)
ggplot(data = survivalTable, mapping = aes(x =duration, y= hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable, mapping = aes(x =duration, y=survival)) +
geom_line()
# now lets do plots for the first two weeks, and the first year
ggplot(data = survivalTable[survivalTable[["duration"]]<=14,], mapping = aes(x =duration, y=hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable[survivalTable[["duration"]]<=14,], mapping = aes(x =duration, y=survival)) +
geom_line()
ggplot(data = survivalTable[survivalTable[["duration"]]<=365,], mapping = aes(x =duration, y=hazard)) +
geom_line() + geom_smooth()
ggplot(data = survivalTable[survivalTable[["duration"]]<=365,], mapping = aes(x =duration, y=survival)) +
geom_line()
# now lets partition by different columns and compute the hazard rates
# partitions: type of school, gender, urbanisation
df[["school_type"]] <- NA
df[["school_type"]][df[["public"]]==1] <- "Public"
df[["school_type"]][df[["catholic"]]==1] <- "Catholic"
df[["school_type"]][df[["protest"]]==1] <- "Protestant"
df[["school_type"]][df[["special"]]==1] <- "Special"
df[["area_type"]] <- NA
df[["area_type"]][df[["urban"]]==1] <- "Urban_1"
df[["area_type"]][df[["urban"]]==2] <- "Urban_2"
df[["area_type"]][df[["urban"]]==3] <- "Urban_3"
df[["area_type"]][df[["urban"]]==4] <- "Urban_4"
df[["area_type"]][df[["urban"]]==5] <- "Urban_5"
df[["gender"]] <- ifelse(df[["gender"]] == 1, "male", "female")
#choose to cut off at 300 because from there the pictures are uninformative
sur_haz_grp("gender", df[df[["splength"]] < 300, ])
sur_haz_grp("area_type", df[df[["splength"]] < 300, ])
sur_haz_grp("school_type", df[!is.na(df[["school_type"]]) & df[["splength"]] < 300, ])
# finally lets test for a difference between the survival rates
survdiff(Surv(splength, rcensor) ~ gender, data=df)
survdiff(Surv(splength, rcensor) ~ urban, data=df)
survdiff(Surv(splength, rcensor) ~ school_type, data=df)
# Question 2 - parametric survival models --------------------------------------
# simple weibull and exponential models
# In order to use the package, we have to make a status indicator
df$status <- ifelse(df$rcensor == 1, 0, 1)
exp_mod <- survreg(Surv(splength, status) ~ public, data=df, dist="exponential")
summary(exp_mod)
weib_mod <- survreg(Surv(splength, status) ~ public, data=df, dist="weibull")
summary(weib_mod)
paste("The scale parameter alpha is: ", 1/weib_mod$scale)
#Note the scale parameter should be intepreted as 1/(rweibull shape)
#The rweibull function is: https://en.wikipedia.org/wiki/Weibull_distribution
#There, we have shape parameter k, which corresponds to our alpha.
#In the example above, the scale is 1.64, so k = 1/1.64
#Thus, k < 1, i.e. decreasing hazard over time (which makes sense)
# now we add some more regressors
weib_mod_2 <- survreg(Surv(splength, status) ~ gender+ public, data=df, dist="weibull")
print(1/weib_mod_2$scale) #no change
summary(weib_mod_2) #negative effect of being male on sickness, public insignificant
weib_mod_3 <- survreg(Surv(splength, status) ~ gender + urban + public,
data=df, dist="weibull")
print(1/weib_mod_3$scale) #again no difference
summary(weib_mod_3) #effect of male still the same, urban/public is insignificant
weib_mod_4 <- survreg(Surv(splength, status) ~ gender + urban + public + catholic +
protest + special, data=df, dist="weibull")
summary(weib_mod_4) #only male and special schools differ a lot in duration
print(1/weib_mod_3$scale) #still no change
# now lets plot the models separately by gender and see if the parameters are
# significantly different using the log-rank test
weib_mod_gen_1 <- survreg(Surv(splength, status) ~ urban + public + catholic +
protest + special, data=df[df[["gender"]]=="male",], dist="weibull")
summary(weib_mod_gen_1)
weib_mod_gen_1$scale
weib_mod_gen_2 <- survreg(Surv(splength, status) ~ urban + public + catholic +
protest + special, data=df[df[["gender"]]== "female",], dist="weibull")
summary(weib_mod_gen_2)
#weib_diff <- survdiff(Surv(splength, status) ~ gender, data=df, dist="weibull")
#I am not really sure how to test difference between the two,
#but I think just looking at the different scale values already gives us
#a reason why to prefer the gender-separate models
#We also look at 'special', because these seem to have different sickness behaviour as well
#
weib_mod_special_1 <- survreg(Surv(splength, status) ~ urban+gender, data=df[df[["special"]]=="1",], dist="weibull")
summary(weib_mod_special_1)
print(1/weib_mod_special_1$scale)
weib_mod_special_2 <- survreg(Surv(splength, status) ~ urban + gender, data=df[df[["special"]]=="0",], dist="weibull")
print(1/weib_mod_special_2$scale)
#indeed, their shape parameters are far apart
# Code for question 3
# Question 3 - piecewise constant ----------------------------------------------
#We follow: https://data.princeton.edu/wws509/r/recidivism
# Fitting piece-wise linear models
#PWC <- function(breaks, df, controls = NULL){
#splitted <- survSplit(Surv(splength, status) ~ ., data = df,
#cut = breaks, episode = "interval", start = "start")
#splitted <- mutate(splitted, exposure = splength - start,
#interval = factor(interval,
#labels = paste("(", c(1,breaks), ",",
#c(breaks,998), "]", sep=""))) %>%
#rename(events = status)
#if(is.null(controls)){
#PWC <- glm(events ~ interval + offset(log(exposure)), data=splitted, family=poisson)
#} else {
#dep_vars <- paste(c("interval", "offset(log(exposure))", controls), collapse="+")
#formula_string <- as.formula(paste("events", dep_vars, sep="~"))
#PWC <- glm(formula_string, data=splitted, family=poisson)
#}
#maxDuration <- max(df[["splength"]])
#b = coef(PWC)[1: length(unique(splitted$interval))]
#h = exp( b)
#lengths <- c(breaks, maxDuration) - c(1, breaks)
#H = cumsum( lengths*h)
#S = exp(-H)
#output <- list(S, PWC)
#return(output)
#}
#plotPWC <- function(breaks, S, maxDuration, subset){
#xgrid <- c(1,breaks, maxDuration) #returns the cut points
#ygrid <- S #returns the corresponding hazards
#graph <- data.frame(x = seq(1, maxDuration, by = 0.1))
#for(i in 1:length(graph$x)){
#for(j in 2:length(xgrid)){
#if(graph$x[i] < xgrid[j] & graph$x[i] >= xgrid[j-1]){
#graph$y[i] <- ygrid[[j-1]]
#}
#}
#}
#p <- ggplot(graph[ graph$x < subset, ]) +
#geom_line(aes(x = x, y = y)) +
#xlab("duration") +
#ylab("survival")
#return(p)
#}
#breaks1 <- c(2, 5, 10, 20, 50, 500)
#breaks2 <- c(2, 3,4,5, 8, 16, 32, 64, 128, 256, 512)
#controls <- c("gender", "urban", 'public',"catholic", "protest", "special")
#S1 <- PWC(breaks1, df)[[1]]
#plotPWC(breaks1, S1, maxDuration, subset = 50)
#S2 <- PWC(breaks2, df)[[1]]
#plotPWC(breaks2, S2, maxDuration, subset = 50)
#S3 <- PWC(breaks2, df, controls)[[2]]
#summary(S3) #once again, only Males and Special have significant signs, but now reversed!
# breaks3 <- c(0, 1,2,3,4,5, 10, 15, 20, 50, 100, 500, 998)
# S4 <- pchreg(Surv(splength, status) ~ gender + urban + public + catholic +
# protest + special, breaks3, data = df)
# S4$beta
# Previous code - piecewise constant ----------------------------------------------
piece_mod_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 4, data=df)
summary(piece_mod_1)
piece_mod_2 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df)
summary(piece_mod_2)
piece_mod_gen_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df[df[["gender"]]==1,])
piece_mod_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 4, data=df)
summary(piece_mod_1)
piece_mod_2 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df)
summary(piece_mod_2)
piece_mod_gen_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df[df[["gender"]]==1,])
View(df)
piece_mod_gen_1 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df[df[["gender"]]=="male",])
summary(piece_mod_gen_1)
piece_mod_gen_2 <- pchreg(Surv(splength, rcensor) ~ 1, breaks = 20, data=df[df[["gender"]]=="female",])
summary(piece_mod_gen_2)
install.packages("bookdown")
library(bookdown)
bookdown::render_book("index.Rmd")
install.packages("bookdown")
install.packages("bookdown")
library(bookdown)
bookdown::render_book("index.Rmd")
install.packages("bookdown")
install.packages("bookdown")
library(bookdown)
bookdown::render_book("index.Rmd")