-
Notifications
You must be signed in to change notification settings - Fork 0
/
Odds_ratio_VIF
60 lines (50 loc) · 1.94 KB
/
Odds_ratio_VIF
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
# Calculate odds ratio for multivariate version and variance inflation factor (VIF). The function exports csv.
odds<-function(df,digit=2,p_r=4,formula,name="Odds_ratio"){
library(car)
library(dplyr)
target=as.character(formula[[2]])
y=df[[target]]
tmp<-NA
for (i in 1:length(df)){
if (length(unique(df[,i]))<3){
tmp[i]<-0
} else{
tmp[i]<-1
}
}
df<-df[,sort(tmp,index.return=TRUE,decreasing=TRUE)$ix]
df %>% relocate(target, .after = last_col())
multi_odds<-array(NA,dim=c((length(df)),2))
multi_model<-glm(formula=formula, data=df,family="binomial")
result<-summary(multi_model)$coefficients[2:length(df),]
result<-cbind(result,result[,1]-1.96*result[,2])
result<-cbind(result,result[,1]+1.96*result[,2])
result<-result[,c(1,5,6,4)]
result[,1:3]<-round(exp(result[,c(1:3)]),digit)
result[,4]<-round(result[,4],p_r)
multi_odds[1:(length(df)-1),1]<-paste0(result[,1]," (",result[,2]," - ",result[,3],")")
multi_odds[1:(length(df)-1),2]<-paste0(result[,4])
multi_odds[length(df),1]<-length(df[,1])
single_odds<-array(NA,dim=c((length(df)),2))
for (i in 1:(length(df)-1)){
single_model<-glm(formula=y ~ df[,i],family="binomial")
result<-summary(single_model)$coefficients[2,]
result<-c(result,result[1]-1.96*result[2])
result<-c(result,result[1]+1.96*result[2])
result<-result[c(1,5,6,4)]
result[1:3]<-round(exp(result[c(1:3)]),digit)
result[4]<-round(result[4],p_r)
single_odds[i,1]<-paste0(result[1]," (",result[2]," - ",result[3],")")
single_odds[i,2]<-paste0(result[4])
}
single_odds[length(df),1]<-length(df[,1])
name<-paste0(name,".csv")
model<-lm(y~.,data=df)
VIF<-c(vif(model))
VIF[length(df)]<-NA
odds_data<-data.frame(multi_odds,single_odds,VIF)
colnames(odds_data)<-c("Multi OR (2.5% - 97.5%)", "p-value","Single OR (2.5% - 97.5%)", "p-value", "vif")
rownames(odds_data)<-c(colnames(df)[1:(length(df)-1)],"total_num")
odds_data
write.csv(odds_data,name)
}