May the Forth be with You (Term project)

May 4th, 2017

A new day begins, so keep working~


Today's mission:

  1. Finish the Introduction of the paper.
  2. Go to the gym for at least half an hour.
  3. To be continued (maybe a movie?)

The final project for the OCN course

title: "Term Project - Part 3"
subtitle: OCN 682 Introduction to Programming & Statistics in R


Instructor: A.B. Neuheimer

Name: Zhenning Li


INITIALIZATION

rm(list=ls())
require(ggplot2)
require(MASS)
require(car)
require(rms)
require(lme4)
require(MuMIn)
require(visreg)
#As we discussed, I first used the MASS package, but the model result cannot be used for analyzing the residuals and so on. So I changed to the rms package. 

DATA

dat=read.csv("C:/Users/User/Google Drive/FIN (Research)-For Zhenning/rural_single_2010-2012_rain.csv")
dat1=dat[,c("sev","dar","daw","dal","mal","fem","you","mid","old")] 
#sev-seveirty; dar-dark; daw-dawn; dal-daylight; mal-male; fem-female; you-young; mid-middle; old-old
#The data is differnet with what we dicussed before because I was not allowed to use that data for other use. Therefore, I changed a very similar data for this project. However, the data doesn't contain the detail age of each individual driver, and the age has already changed into catergorcial. The young here means drivers less than 25 years old, middle means drivers are between 26 to 65 years, and the old means the drivers are older than 65 years. 
#In order to make the data more clearly, I changed the numeric data into factors.
for (i in 1:length(dat1[1,])){
  dat1[,i]=as.factor(dat1[,i])
}

lapply(dat1[, c(1:9)], table)
#sev is categorical without unit and the levels of it are 1, 2, 3, and 4, indicating no injury, minor injury, major injury, and fatal, respectively.
#dar, dal, mal, fem, you, mid, and old are all binary where 1 stands for the crash record has this kind of character, and 0 means the thing didn't happen.

#just in case I need lm() to fit the model
dat2=dat[,c("sev","dar","daw","dal","mal","fem","you","mid","old")] 

RESPONSE(S)

What:

The "sev" is the response, it is categorical with four levels.

Motivation:

The severity varies in different traffic crashes because of multiple reasons. Thus, analyzing the reasons of it benefits for the traffic safety.


PREDICTOR(S)

What:

dar, dal, daw, mal, fem, you, mid, and old are the predictors. They are all binary where 1 stands for the crash record has this kind of character, and 0 means the thing didn't happen.

Mechanisms:

Previous studies showed that the driver age is one of the most important contributions to the crash severity. However, the influence mechanism is not clear yet, i.e., the young drivers are more likely to get involved in level 3 accidents but less likely in level 2 accident according to some reports. Thus, I decided to analyze the relationship between the severity and the driver age. Besides, the driver gender together with the light condition may also influence the severity.


HYPOTHESIS

sev~ dar+dal+daw+mal+fem+you+mid+old


STARTING MODEL

Error distribution assumption:

As we discussed before, the error distribution is a multinomial distribution since the multinomial distribution gives the probability of any particular combination of numbers of successes for the various categories.

Shape assumption:

The relationship between the response and the predictors are non-linear. Since the nature of the response is a factor with four ordered levels and the natures of all the predictors are categorical, I decided to choose the ordinal logistic regression.

Fit your starting model:

## fit ordered logit model and store results 'm1', this package can use residual plot, but cannot use the predict
m1=orm(sev~ dar + daw + mal + you + old, data = dat1, x=TRUE, y=TRUE) #In case of rank-deficient, several predictors are deleted. Therefore, the final model is sev~ dar + daw + mal + you + old.
show(m1)
## fit ordered logit model in the other package, the package can use the the predict, but cannot use the residual plot
mx=polr(as.factor(sev)~ dar + daw + mal + you + old, data = dat2)

coeff<-rbind(coef(m1)[-c(1:3)],coef(mx))
##The results are the same

ASSESSING FIT

Predictor multicollinearity:

Are there any issues with predictor multicollinearity? If yes, what do you do?

vif(m1) #All the vif is less than 3 suggesting that the model has no multicollinearity. But I am not sure about whether there is multicollinearity or not in this kind of crash data (we have quite a lot). First, the predictors didn't have any obvious interrelationships between each other since the crashes happen in different places and a different time. I found by Google that somebody said that when using the OLR model, the vif less than 8 means there are no multicollinearity. Besides, somebody also suggested that using the lm() function to find whether the predictors have multicollinearity or not.Therefore, I also designed a linear model.  
m2<-lm(sev~ dar + daw + mal + you + old, data = dat2)
vif(m2) #The vifs of all the predictors are quite small. Therefore, the m1 model is a good fit model. 

Assessing residuals:

par(mfrow=c(2,4))
colName<-colnames(dat1)
#There are no residual plots for this kind of model, so I tired to use this way to show residuals.
for(i in 2:9){
  plot(dat1[,i], resid(m1, type="li.shepherd"),
       xlab=colName[i],
     ylab="li.shepherd residual")
lines(lowess(dat1[,i], resid(m1, type="li.shepherd")))
points(dat1[,i], resid(m1, type="li.shepherd"))
}
#From the figures we can see that, the means of each box are all near to zero indicating that the residuals are relatively equal. 
par(mfrow=c(1,1))
#Besides, I think this one can also be used as residuals. 
plot(resid(m1, type="li.shepherd")) #I think the residuals are good enough. 

MODEL SELECTION

#Fit a linear model
m2<-lm(sev~ dar + daw + mal + you + old, data = dat2)
#Fit a mixed model, the relationship between male and different age are examined.
m3<-lmer(sev~ dar + daw + (mal|you) + (mal|old),data=dat2) 
#model.sel()is not aviable here, so I use the AIC() instead.
AIC(m1)->AICm1; AIC(m2)->AICm2; AIC(m3)->AICm3
order(c(AICm1,AICm2,AICm3)) #The OLR model has the smallest AIC, therefore, it is the best model for this problem

VISUALIZATION

Include at least one visualization showing some aspect of your data as well as your model's fit.
BONUS: Include a map/chart somehow relevant to your term project.

# estimates the values that will be graphed
sf <- function(y) {
  c('Y>=1' = qlogis(mean(y >= 1)),
    'Y>=2' = qlogis(mean(y >= 2)),
    'Y>=3' = qlogis(mean(y >= 3)),
    'Y>=4' = qlogis(mean(y >= 4)))
}
# Plot the mean of the data in log scale
s <- with(dat1, summary(as.numeric(sev) ~ dar + daw + mal + you + old, fun=sf))
s[, 5] <- s[, 5] - s[, 4]
s[, 4] <- s[, 4] - s[, 3]
s[, 3] <- s[, 3] - s[, 3]
plot(s, which=1:4, pch=1:4, xlab='logit', main=' ', xlim=range(s[,3:5]))
# Visualizing the fit model
visreg(m1)

REPORTING

##Predict
newdat <- 1-dat2[c(20:5000),-1]
newdat <- cbind(newdat, predict(mx, newdat, type = "probs"))

##show first few rows
head(newdat)

lnewdat <- melt(newdat, id.vars = c("dar", "daw", "dal","mal","fem","you","mid","old"),
  variable.name = "Level", value.name="Probability")
for (i in 1:length(lnewdat[1,])){
  lnewdat[,i]=as.factor(lnewdat[,i])
}
## view first few rows
head(lnewdat)

##Plot the prediction
ggplot(lnewdat, aes(x = mid, y = as.numeric(Probability), colour = Level)) +
  geom_boxplot() + facet_grid(dal ~ mal, labeller="label_both")
# From the plot, we can see that 
# 1) When a driver is a middle-age person, the probabilities of the level 1 crashes are decreasing in all the four figures, indicating that the middle-age drivers are more likely to get involved in severe crashes when being compared to other age groups.
# 2) When the light condition is daylight, the drivers are more unlikely to be injured. The reason may be that in the daytime, the drivers usually drive at smaller speeds and more likely to follow the traffic rules. Besides, the high traffic volumes may also be another contributor that the congestion may 'protect' the drivers to some extent. 
# 3) The male drivers seem much safer than the female drivers. Their possibilities of getting involved in level 1 crashes are much smaller than those of female drivers. More research should be conducted on analyzing the underlying reasons. 

END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容