-
Notifications
You must be signed in to change notification settings - Fork 0
/
sar_vifs.R
92 lines (76 loc) · 2.48 KB
/
sar_vifs.R
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
## calculating vifs for SAR error models
## 30 / 07 / 2014
## Isabel Fenton
source("C:/Documents/Science/PhD/Code/lr_calculations.R")
vif.sar <- function(model, data) {
evs <- model.evs(model)
evs <- gsub("poly\\(", "", evs)
evs <- gsub("\\,.*", "", evs)
evs <- unique(evs)
data2 <- data[, evs]
if (length(as.character(model$call)) > 5) warning("Only tested with 4 inputs")
mod.call <- as.character(model$call)
# identify the tolerance from the model
tmp <- grep("[0-9]", mod.call)
if (length(tmp) == 1) {
tol <- as.numeric(mod.call[tmp])
} else if (length(tmp) == 0) {
tol <- 1e-10
} else {
tol <- as.numeric(mod.call[tmp[1]])
print("Taking tol.solve as ", tol.solve, ". Is this correct?")
}
# identify the listw
listw.num <- which(unlist(lapply(mod.call, function(x) class(eval(parse(text = x))))) == "listw")
listw.val <- mod.call[listw.num]
# generate the output
out <- rep(NA, length(evs))
names(out) <- evs
for (i in evs) {
if (is.factor(data2[, i])) {
out[i] <- NA
} else {
# calculate the vif for each ev
tmp.mod <- errorsarlm(data2[, i] ~ ., eval(parse(text = listw.val)), tol.solve = tol, zero.policy = model$zero.policy, data = data2[, -which(names(data2) == i)])
out[i] <- 1 / (1 - summary(tmp.mod, Nagelkerke = TRUE)$NK)
}
}
return(out)
}
vif.lmt <- function(model, data) {
evs <- model.evs(model)
evs <- gsub("poly\\(", "", evs)
evs <- gsub("\\,.*", "", evs)
evs <- unique(evs)
data2 <- data[, evs]
#if (length(as.character(model$call)) > 5) warning("Only tested with 4 inputs")
#mod.call <- as.character(model$call)
# identify the tolerance from the model
# tmp <- grep("[0-9]", mod.call)
# if (length(tmp) == 1) {
# tol <- as.numeric(mod.call[tmp])
# } else if (length(tmp) == 0) {
# tol <- 1e-10
# } else {
# tol <- as.numeric(mod.call[tmp[1]])
# print("Taking tol.solve as ", tol.solve, ". Is this correct?")
# }
#
# # identify the listw
# listw.num <- which(unlist(lapply(mod.call, function(x) class(eval(parse(text = x))))) == "listw")
# listw.val <- mod.call[listw.num]
#
# # generate the output
out <- rep(NA, length(evs))
names(out) <- evs
for (i in evs) {
if (is.factor(data2[, i])) {
out[i] <- NA
} else {
# calculate the vif for each ev
tmp.mod <- glm(data2[, i] ~ ., data = data2[, -which(names(data2) == i)])
out[i] <- 1 / (1 - NagelkerkeR2(tmp.mod)$R2)
}
}
return(out)
}