-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions_flexnoX.R
123 lines (72 loc) · 1.97 KB
/
functions_flexnoX.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
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
#estimation of the weak instrument F through minimisation of Q to estimate delta.
Q_ind = function(a){
d1 = a[1]
w = 1/(stderr[,1]^2- 2*d1*cov + (d1^2)*stderr[,2]^2)
q = sum(w*(pihat[,1] - (d1*pihat[,2]))^2)
}
Q_ind2 = function(a){
d2 = a[1]
w = 1/(stderr[,2]^2- 2*d2*cov + (d2^2)*stderr[,1]^2)
q = sum(w*(pihat[,2] - (d2*pihat[,1]))^2)
}
#Estimation of beta through minimisation of the Q statistic - no heterogeneity
LIML_b = function(ab){
b=ab
cov = matrix(nrow = kx, ncol = kx)
w=NULL
for(l in 1:L){
for(pp in 1:kx){
for(p2 in 1:kx){
cov[pp,p2] <- correlation[pp,p2]*stderr[l,pp]*stderr[l,p2]
}
}
w[l] <- segamma[l]^2+t(b)%*%cov%*%b
}
q = sum((1/w)*((gammahat - pihat%*%b)^2))
}
#estimation with the heterogeneity statistic
PL_MVMR = function(a){
tau2 = a[1]
PL2_MVMR = function(ab){
b=ab
cov = matrix(nrow = kx, ncol = kx)
w=NULL
for(l in 1:L){
for(pp in 1:kx){
for(p2 in 1:kx){
cov[pp,p2] <- correlation[pp,p2]*stderr[l,pp]*stderr[l,p2]
}
}
w[l] <- segamma[l]^2+t(b)%*%cov%*%b + tau2
}
q = sum((1/w)*((gammahat - pihat%*%b)^2))
}
st_PL2 = rep(0,kx)
bc = optim(st_PL2, PL2_MVMR)
bcresults <- bc$par
cov = matrix(nrow = kx, ncol = kx)
w=NULL
for(l in 1:L){
for(pp in 1:kx){
for(p2 in 1:kx){
cov[pp,p2] <- correlation[pp,p2]*stderr[l,pp]*stderr[l,p2]
}
}
w[l] <- segamma[l]^2+t(bcresults)%*%cov%*%bcresults + tau2
}
q = (sum((1/w)*((gammahat - pihat%*%bcresults)^2))-(L-kx))^2
}
PL2_MVMR = function(ab){
b=ab
w=NULL
cov = matrix(nrow = kx, ncol = kx)
for(l in 1:L){
for(pp in 1:kx){
for(p2 in 1:kx){
cov[pp,p2] <- correlation[pp,p2]*stderr[l,pp]*stderr[l,p2]
}
}
w[l] <- segamma[l]^2+t(b)%*%cov%*%b + tau_i
}
q = sum((1/w)*((gammahat - pihat%*%b)^2))
}