Skip to content

Instantly share code, notes, and snippets.

@grayclhn
Last active December 28, 2015 17:32
Show Gist options
  • Save grayclhn/59aada5d070b9a923c81 to your computer and use it in GitHub Desktop.
Save grayclhn/59aada5d070b9a923c81 to your computer and use it in GitHub Desktop.
Temporary mirror of the R code from CCT's rdrobust package (for linking and commenting purposes). The full version of this package is available at https://sites.google.com/site/rdpackages/rdrobust
### version 0.1 18Nov2013
### version 0.2 26Nov2013
### version 0.3 21Abr2014
### version 0.5 06Jun2014
### version 0.6 17Jun2014
### version 0.61 03Sep2014
### version 0.7 14Oct2014
### version 0.8 04Feb2015
qrXXinv = function(x, ...) {
#tcrossprod(solve(qr.R(qr(x, tol = 1e-10)), tol = 1e-10))
#tcrossprod(solve(qr.R(qr(x))))
chol2inv(chol(crossprod(x)))
}
qrreg = function(x,y,w,s2=0,var.comp=TRUE, ...) {
M.X = sqrt(w)*x
X.M.X_inv = qrXXinv(M.X)
X.M.Y = crossprod(M.X,sqrt(w)*y)
beta.hat = X.M.X_inv%*%X.M.Y
Psi.hat=Sigma.hat=0
if (var.comp==TRUE) {
Psi.hat = crossprod((w*s2*w)*x,x)
Sigma.hat = crossprod(Psi.hat%*%X.M.X_inv,X.M.X_inv)
}
output = list(X.M.X_inv=X.M.X_inv, X.M.Y=X.M.Y, beta.hat=beta.hat, Psi.hat=Psi.hat, Sigma.hat=Sigma.hat)
return(output)
}
kweight = function(X, c, h, kernel){
u = (X-c)/h
if (kernel=="epanechnikov" | kernel=="epa") {
w = (0.75*(1-u^2)*(abs(u)<=1))/h
}
else if (kernel=="uniform" | kernel=="uni") {
w = (0.5*(abs(u)<=1))/h
}
else {
w = ((1-abs(u))*(abs(u)<=1))/h
}
return(w)
}
bwconst = function(p,v,kernel){
if (kernel=="epanechnikov" | kernel=="epa" | kernel==3) {
K.fun = function(u) {(0.75*(1-u^2)*(abs(u)<=1))}
}
else if (kernel=="uniform" | kernel=="uni" | kernel==2) {
K.fun = function(u) {(0.5*(abs(u)<=1))}
}
else {
K.fun = function(u) {((1-abs(u))*(abs(u)<=1))}
}
p1 = p+1
Gamma_p = Phi_p = matrix(NA,p1,p1)
Omega_pq = matrix(NA,p1,1)
for (i in 1:p1) {
Omega.fun = function(u) {K.fun(u)*(u^(p1))*(u^(i-1))}
Omega_pq[i] = integrate(Omega.fun,lower=0,upper=1)$value
for (j in 1:p1) {
Gamma.fun = function(u) {K.fun(u)*(u^(i-1))*(u^(j-1))}
Phi.fun = function(u) {(K.fun(u)^2)*(u^(i-1))*(u^(j-1))}
Gamma_p[i,j] = integrate(Gamma.fun,lower=0,upper=1)$value
Phi_p[i,j] = integrate(Phi.fun,lower=0,upper=1)$value
}
}
B_const = solve(Gamma_p)%*%Omega_pq
V_const = solve(Gamma_p)%*%Phi_p%*%solve(Gamma_p)
C1 = B_const[v+1,1]
C2 = V_const[v+1,v+1]
return(c(C1,C2))
}
rdvce= function(X,y,frd=NULL,p,h,matches,vce,kernel){
m = matches+1
n = length(X)
p1 = p+1
sigma = matrix(0,n,1)
if (vce=="resid") {
for (k in 1:n) {
cutoff = matrix(X[k],n,1)
cutoff1 = X[k]
W = kweight(X,cutoff1,h,"kernel")
ind=W>0
if (sum(ind)>5) {
w.p=W[ind]; X.p=X[ind]; y.p=y[ind]
XX.p = matrix(c((X.p-cutoff1)^0, poly(X.p-cutoff1,degree=p,raw=T)),length(X.p),p+1)
mu0_phat_y = qr.coef(qr(XX.p*sqrt(w.p), tol = 1e-10), sqrt(w.p)*y.p)[1]
if (is.null(frd)) {
sigma[k] = (y[k] - mu0_phat_y)^2
}
else if (!is.null(frd)) {
z.p=frd[ind]
out=qrreg(XX.p, z.p, w.p, var.comp=FALSE)
mu0_phat_z = out$beta.hat[1]
sigma[k] = (y[k] - mu0_phat_y)*(frd[k] - mu0_phat_z)
}
}
}
}
else {
#y_match_avg = z_match_avg = matrix(NA,n,1)
for (k in 1:n) {
diffx = abs(X - X[k])
m.group = sort(unique(diffx))[2:m]
ind = which(diffx %in% m.group)
y_match_avg = z_match_avg = mean(y[ind])
Ji = length(ind)
if (is.null(frd)) {
sigma[k] = (Ji/(Ji+1))*(y[k] - y_match_avg)^2
}
else if (!is.null(frd)) {
z_match_avg = mean(frd[ind])
sigma[k] = (Ji/(Ji+1))*(y[k] - y_match_avg)*(frd[k] - z_match_avg)
}
}
}
return(sigma)
}
regconst = function(d,h){
d2 = 2*d+1
d1 = d+1
mu = matrix(0,d2, 1)
mu[1] = 1
XX = matrix(0,d1,d1)
for (j in 2:d2) {
i = j-1
if (j%%2==1) {
mu[j] = (1/(i+1))*(h/2)^i
}
}
for (j in 1:d1) {
XX[j,] = t(mu[j:(j+d)])
}
invXX =solve(XX)
return(invXX)
}
### Copyright (c) Sebastian Calonico <scalonico@bus.miami.edu>,
### Matias D. Cattaneo <cattaneo@umich.edu>,
### Rocio Titiunik <titiunik@umich.edu>
###
### This file is part of the rdrobust R package.
###
### Rdrobust is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, version 2 of the License.
###
### Rdrobust is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with rdrobust. If not, see <http://www.gnu.org/licenses/>.
### version 0.1 18Nov2013
### version 0.2 26Nov2013
### version 0.3 21Abr2014
### version 0.5 06Jun2014
### version 0.6 17Jun2014
### version 0.61 03Sep2014
rdbinselect = function(y, x, subset = NULL, c=0, p=4, numbinl=NULL, numbinr=NULL,
binselect="es", lowerend=NULL, upperend=NULL, scale=1,
hide=FALSE, par=NULL, title=NULL, x.label=NULL, y.label=NULL,
x.lim=NULL, y.lim=NULL) {
call <- match.call()
#if (missing(data))
#data <- environment(formula)
if (!is.null(subset)) {
x <- x[subset]
y <- y[subset]
}
na.ok <- complete.cases(x) & complete.cases(y)
x <- x[na.ok]
y <- y[na.ok]
#if (frame) {
# dat.out <- data.frame(x, y)
#}
if (is.null(lowerend)) {
lowerend = min(x)
}
if (is.null(upperend)) {
upperend = max(x)
}
x_low = lowerend
x_upp = upperend
size=sum(x>=x_low & x<=x_upp)
y=y[x>=x_low & x<=x_upp]
x=x[x>=x_low & x<=x_upp]
x_l = x[x<c]; x_r = x[x>=c]
y_l = y[x<c]; y_r = y[x>=c]
x.min = min(x); x.max = max(x)
range_l = max(x_l) - min(x_l)
n_l = length(x_l)
range_r = max(x_r) - min(x_r)
n_r = length(x_r)
n = n_l + n_r
#####********************* ERRORS
exit=0
if (c<=x.min | c>=x.max){
print("c should be set within the range of x")
exit = 1
}
if (p<=0 ){
print("p should be a positive number")
exit = 1
}
if (scale<=0 ){
print("scale should be a positive number")
exit = 1
}
p_floor = floor(p)/p
if (p_floor!=1) {
print("p should be an integer number")
exit = 1
}
if (exit>0) {
stop()
}
p1 = p+1
compute =0
rp_l = matrix(NA,n_l,p1); rp_r = matrix(NA,n_r,p1)
for (j in 1:p1) {
rp_l[,j] = x_l^(j-1)
rp_r[,j] = x_r^(j-1)
}
gamma_p1_l = lm(y_l~rp_l-1)$coeff
gamma_p1_r = lm(y_r~rp_r-1)$coeff
mu0_p1_l = rp_l%*%gamma_p1_l; mu0_p1_r = rp_r%*%gamma_p1_r
J_star_l_orig=numbinl
J_star_r_orig=numbinr
if (is.null(J_star_l_orig) & is.null(J_star_l_orig)) {
compute = 1
y_l.sq = y_l^2
y_r.sq = y_r^2
gamma_p2_l = lm(y_l.sq~rp_l-1)$coeff
gamma_p2_r = lm(y_r.sq~rp_r-1)$coeff
### Bias w/sample
drp_l = matrix(NA,n_l,p); drp_r = matrix(NA,n_r,p)
for (j in 1:p) {
drp_l[,j] = j*x_l^(j-1)
drp_r[,j] = j*x_r^(j-1)
}
mu1_hat_l = drp_l%*%(gamma_p1_l[2:p1])
mu1_hat_r = drp_r%*%(gamma_p1_r[2:p1])
######################### ES
ind.l = order(x_l); ind.r = order(x_r)
x.i.l = x_l[ind.l]; x.i.r = x_r[ind.r]
y.i.l = y_l[ind.l]; y.i.r = y_r[ind.r]
dxi.l=(x.i.l[2:length(x.i.l)]-x.i.l[1:(length(x.i.l)-1)])
dxi.r=(x.i.r[2:length(x.i.r)]-x.i.r[1:(length(x.i.r)-1)])
dyi.l=(y.i.l[2:length(y.i.l)]-y.i.l[1:(length(y.i.l)-1)])
dyi.r=(y.i.r[2:length(y.i.r)]-y.i.r[1:(length(y.i.r)-1)])
x.bar.i.l = (x.i.l[2:length(x.i.l)]+x.i.l[1:(length(x.i.l)-1)])/2
x.bar.i.r = (x.i.r[2:length(x.i.r)]+x.i.r[1:(length(x.i.r)-1)])/2
rp.i_l = matrix(NA,n_l-1,p+1); rp.i_r= matrix(NA,n_r-1,p+1)
drp.i_l = matrix(NA,n_l-1,p); drp.i_r = matrix(NA,n_r-1,p)
for (j in 1:p1) {
rp.i_l[,j] = x.bar.i.l^(j-1)
rp.i_r[,j] = x.bar.i.r^(j-1)
}
for (j in 1:p) {
drp.i_l[,j] = j*x.bar.i.l^(j-1)
drp.i_r[,j] = j*x.bar.i.r^(j-1)
}
mu0.i_hat_l = rp.i_l%*%gamma_p1_l; mu0.i_hat_r = rp.i_r%*%gamma_p1_r
mu1.i_hat_l = drp.i_l%*%(gamma_p1_l[2:p1]); mu1.i_hat_r = drp.i_r%*%(gamma_p1_r[2:p1])
mu2.i_hat_l = rp.i_l%*%gamma_p2_l; mu2.i_hat_r = rp.i_r%*%gamma_p2_r
sigma2_hat_ul = mu2.i_hat_l - mu0.i_hat_l^2
sigma2_hat_ur = mu2.i_hat_r - mu0.i_hat_r^2
B.es.hat.l = ((c-x.min)^2/12)*sum(dxi.l*mu1.i_hat_l^2)
B.es.hat.r = ((x.max-c)^2/12)*sum(dxi.r*mu1.i_hat_r^2)
V.es.hat.l = (n/(4*(c-x.min)))*sum(dxi.l^2*dyi.l^2)
V.es.hat.r = (n/(4*(x.max-c)))*sum(dxi.r^2*dyi.r^2)
C.es.hat.l = (2*B.es.hat.l)/V.es.hat.l
C.es.hat.r = (2*B.es.hat.r)/V.es.hat.r
J.es.hat.l = floor((C.es.hat.l*(n_l+n_r))^(1/3))
J.es.hat.r = floor((C.es.hat.r*(n_l+n_r))^(1/3))
V.es.chk.l = (n/(2*(c-x.min)))*sum(dxi.l^2*sigma2_hat_ul)
V.es.chk.r = (n/(2*(x.max-c)))*sum(dxi.r^2*sigma2_hat_ur)
C.es.chk.l = (2*B.es.hat.l)/V.es.chk.l
C.es.chk.r = (2*B.es.hat.r)/V.es.chk.r
J.es.chk.l = floor((C.es.chk.l*(n_l+n_r))^(1/3))
J.es.chk.r = floor((C.es.chk.r*(n_l+n_r))^(1/3))
B.es.hat.dw.l = ((c-x.min)^2/(12*n))*sum(mu1.i_hat_l^2)
B.es.hat.dw.r = ((x.max-c)^2/(12*n))*sum(mu1.i_hat_r^2)
V.es.hat.dw.l = (0.5/(c-x.min))*sum(dxi.l*dyi.l^2)
V.es.hat.dw.r = (0.5/(x.max-c))*sum(dxi.r*dyi.r^2)
C.es.hat.dw.l = (2*B.es.hat.dw.l)/V.es.hat.dw.l
C.es.hat.dw.r = (2*B.es.hat.dw.r)/V.es.hat.dw.r
J.es.hat.dw.l = floor((C.es.hat.dw.l*(n_l+n_r))^(1/3))
J.es.hat.dw.r = floor((C.es.hat.dw.r*(n_l+n_r))^(1/3))
######################### QS
V.qs.hat.l = (n/(2*n_l))*sum(dxi.l*dyi.l^2)
V.qs.hat.r = (n/(2*n_r))*sum(dxi.r*dyi.r^2)
B.qs.hat.l = (n_l^2/72)*sum(dxi.l^3*mu1.i_hat_l^2)
B.qs.hat.r = (n_r^2/72)*sum(dxi.r^3*mu1.i_hat_r^2)
C.qs.hat.l = (2*B.qs.hat.l)/V.es.hat.l
C.qs.hat.r = (2*B.qs.hat.r)/V.es.hat.r
J.qs.hat.l = floor((C.qs.hat.l*(n_l+n_r))^(1/3))
J.qs.hat.r = floor((C.qs.hat.r*(n_l+n_r))^(1/3))
V.qs.chk.l = (n/n_l)*sum(dxi.l*sigma2_hat_ul)
V.qs.chk.r = (n/n_r)*sum(dxi.r*sigma2_hat_ur)
C.qs.chk.l = (2*B.qs.hat.l)/V.qs.chk.l
C.qs.chk.r = (2*B.qs.hat.r)/V.qs.chk.r
J.qs.chk.l = floor((C.qs.chk.l*(n_l+n_r))^(1/3))
J.qs.chk.r = floor((C.qs.chk.r*(n_l+n_r))^(1/3))
V.qs.hat.dw.l = (1/(2*n_l))*sum(dxi.l^0*dyi.l^2)
V.qs.hat.dw.r = (1/(2*n_r))*sum(dxi.r^0*dyi.r^2)
B.qs.hat.dw.l = (n_l^1/48)*sum(dxi.l^2*mu1.i_hat_l^2)
B.qs.hat.dw.r = (n_r^1/48)*sum(dxi.r^2*mu1.i_hat_r^2)
C.qs.hat.dw.l = (2*B.qs.hat.dw.l)/V.es.hat.dw.l
C.qs.hat.dw.r = (2*B.qs.hat.dw.r)/V.es.hat.dw.r
J.qs.hat.dw.l = floor((C.qs.hat.dw.l*(n_l+n_r))^(1/3))
J.qs.hat.dw.r = floor((C.qs.hat.dw.r*(n_l+n_r))^(1/3))
if (binselect=="es" ) {
J_star_l_orig = J.es.hat.l
J_star_r_orig = J.es.hat.r
}
if (binselect=="espr") {
J_star_l_orig = J.es.chk.l
J_star_r_orig = J.es.chk.r
}
if (binselect=="esdw") {
J_star_l_orig = J.es.hat.dw.l
J_star_r_orig = J.es.hat.dw.r
}
if (binselect=="qs") {
J_star_l_orig = J.qs.hat.l
J_star_r_orig = J.qs.hat.r
}
if (binselect=="qspr" ) {
J_star_l_orig = J.qs.chk.l
J_star_r_orig = J.qs.chk.r
}
if (binselect=="qsdw" ) {
J_star_l_orig = J.qs.hat.dw.l
J_star_r_orig = J.qs.hat.dw.r
}
}
J_star_l = scale*J_star_l_orig
J_star_r = scale*J_star_r_orig
bin_x_l = rep(0,length(x_l)); bin_x_r = rep(0,length(x_r))
jump_l = range_l/J_star_l;jump_r = range_r/J_star_r;
if (binselect=="es" |binselect=="espr" |binselect=="esdw" ) {
jumps_l=seq(min(x_l),max(x_l),jump_l)
jumps_r=seq(min(x_r),max(x_r),jump_r)
binselect_type="Evenly-Spaced"
}
else if (binselect=="qs" |binselect=="qspr" |binselect=="qsdw" ) {
jumps_l=quantile(x_l,probs=seq(0,1,1/J_star_l))
jumps_r=quantile(x_r,probs=seq(0,1,1/J_star_r))
binselect_type="Quantile-Spaced"
}
for (k in 1:(J_star_l-1)) {
bin_x_l[x_l>=jumps_l[k] & x_l<jumps_l[k+1]] = -J_star_l+k-1
}
bin_x_l[x_l>=jumps_l[(J_star_l)]] = -1
for (k in 1:(J_star_r-1)) {
bin_x_r[x_r>=jumps_r[k] & x_r<jumps_r[k+1]] = k
}
bin_x_r[x_r>=jumps_r[(J_star_r)]] = J_star_r
bin_xlmean=bin_ylmean=rep(0,J_star_l)
bin_xrmean=bin_yrmean=rep(0,J_star_r)
for (k in 1:(J_star_l)) {
bin_xlmean[k]=mean(c(jumps_l[k],jumps_l[k+1]))
#bin_xlmean[k]=mean(x_l[bin_x_l==-k])
bin_ylmean[J_star_l-k+1]=mean(y_l[bin_x_l==-k])
}
for (k in 1:(J_star_r)) {
bin_xrmean[k]=mean(c(jumps_r[k],jumps_r[k+1]))
#bin_xrmean[k]=mean(x_r[bin_x_r==k])
bin_yrmean[k]=mean(y_r[bin_x_r==k])
}
bin_x=c(bin_x_l,bin_x_r)
bin_xmean=c(bin_xlmean,bin_xrmean)
bin_ymean=c(bin_ylmean,bin_yrmean)
x_sup = c(x_l, x_r)
#y_hat = c(mu0_p1_l, mu0_p1_r)
if (hide=="FALSE") {
if (is.null(title)){
title="RD Bin Select"
}
if (is.null(x.label)){
x.label="X axis"
}
if (is.null(y.label)){
y.label="Y axis"
}
if (is.null(x.lim)){
x.lim=c(min(x_l),max(x_r))
}
if (is.null(y.lim)){
y.lim=c(min(c(y_l,y_r)),max(c(y_l,y_r)))
}
par=par
plot(bin_xmean[order(bin_xmean)],bin_ymean[order(bin_xmean)], main=title, xlab=x.label, ylab=y.label, ylim=y.lim, xlim=x.lim, pch=20)
points(x_l[order(x_l)],mu0_p1_l[order(x_l)],type="l")
points(x_r[order(x_r)],mu0_p1_r[order(x_r)],type="l")
abline(v=c)
}
# if (compute==1) {
tabl1.str=matrix(NA,5,2)
tabl1.str[1,] = formatC(c(n_l,n_r),digits=0, format="f")
tabl1.str[2,] = formatC(c(p,p),digits=0, format="f")
tabl1.str[3,] = formatC(c(J_star_l,J_star_r),digits=0, format="f")
tabl1.str[4,] = formatC(c(scale,scale),digits=0, format="f")
tabl1.str[5,] = formatC(c(jump_l,jump_r),digits=4, format="f")
rownames(tabl1.str)=c("Number of Obs.","Poly. Order","Number of Bins","Scale","Bin Length")
colnames(tabl1.str)=c("Left","Right")
results=matrix(NA,5,2)
results[1,] = c(n_l,n_r)
results[2,] = c(p,p)
results[3,] = c(J_star_l,J_star_r)
results[4,] = c(scale,scale)
results[5,] = c(jump_l,jump_r)
rownames(results)=c("Number of Obs.","Poly. Order","Number of Bins","Scale","Bin Length")
colnames(results)=c("Left","Right")
coef=matrix(NA,p+1,2)
coef[,1] = c(gamma_p1_l)
coef[,2] = c(gamma_p1_r)
colnames(coef)=c("Left","Right")
out=list(method=binselect_type,results=results,coef=coef,tabl1.str=tabl1.str)
out$call <- match.call()
class(out) <- "rdbinselect"
return(out)
# }
}
#rdbinselect <- function(y,x, ...) UseMethod("rdbinselect")
#rdbinselect.default <- function(y,x, ...){
# est <- rdbinselectEst(y,x, ... )
# est$call <- match.call()
# class(est) <- "rdbinselect"
# est
#}
print.rdbinselect <- function(x,...){
cat("Call:\n")
print(x$call)
cat("\n")
print(paste("Method: ",x$method),quote=F)
cat("\n\n")
print(x$tabl1.str,quote=F)
}
summary.rdbinselect <- function(object,...) {
TAB <- object$results
res <- list(call=object$call, coefficients=TAB)
class(res) <- "summary.rdbinselect"
res
}
#print.summary.rdbinselect <- function(x, ...){
# cat("Call:\n")
# print(x$call)
# cat("\n")
# printCoefmat(x$coefficients, P.values=FALSE, has.Pvalue=FALSE)
#}
### Copyright (c) Sebastian Calonico <scalonico@bus.miami.edu>,
### Matias D. Cattaneo <cattaneo@umich.edu>,
### Rocio Titiunik <titiunik@umich.edu>
###
### This file is part of the rdrobust R package.
###
### Rdrobust is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, version 2 of the License.
###
### Rdrobust is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with rdrobust. If not, see <http://www.gnu.org/licenses/>.
### version 0.1 18Nov2013
### version 0.2 26Nov2013
### version 0.3 21Abr2014
### version 0.5 06Jun2014
### version 0.6 17Jun2014
### version 0.61 03Sep2014
### version 0.7 14Oct2014
### version 0.8 04Feb2015
rdbwselect = function(y, x, subset = NULL, c=0, p=1, q=2, deriv=0, rho=NULL, kernel="tri", bwselect="CCT", scaleregul=1, delta=0.5, cvgrid_min=NULL, cvgrid_max=NULL, cvgrid_length=NULL, cvplot=FALSE, vce="nn", matches=3, all=FALSE, precalc=TRUE){
call <- match.call()
#if (missing(data))
#data <- environment(formula)
if (!is.null(subset)) {
x <- x[subset]
y <- y[subset]
}
na.ok <- complete.cases(x) & complete.cases(y)
x <- x[na.ok]
y <- y[na.ok]
#if (frame) {
# dat.out <- data.frame(x, y)
#}
b_calc = 0
if (is.null(rho)){
b_calc = 1
rho = 1
}
X_l = x[x<c]; X_r = x[x>=c]
Y_l = y[x<c]; Y_r = y[x>=c]
N_l = length(X_l); N_r = length(X_r)
x_min=min(x); x_max=max(x)
N = N_r + N_l
m = matches + 1
if (precalc=="TRUE"){
#if (deriv==0 & p==0){
# p = 1
#}
if (deriv>0 & p==0){
bwselect = "CCT"
p = deriv+1
}
if (q==0) {
q = p+1
}
exit=0
################# ERRORS
if (kernel!="uni" & kernel!="uniform" & kernel!="tri" & kernel!="triangular" & kernel!="epa" & kernel!="epanechnikov" & kernel!="" ){
print("kernel incorrectly specified")
exit = 1
}
if (bwselect!="CCT" & bwselect!="IK" & bwselect!="CV" & bwselect!=""){
print("bwselect incorrectly specified")
exit = 1
}
if (vce!="resid" & vce!="nn" & vce!="" & vce!="s2.pob"){
print("vce incorrectly specified")
exit = 1
}
if (c<=x_min | c>=x_max){
print("c should be set within the range of x")
exit = 1
}
if (p<=0 | q<=0 | deriv<0 | matches<=0 ){
print("p, q, deriv and matches should be positive integers")
exit = 1
}
if (p>=q & q>0){
print("p should be set higher than q")
exit = 1
}
if (deriv>=p & deriv>0 ){
print("deriv should be set higher than p")
exit = 1
}
p_round = round(p)/p; q_round = round(q)/q; d_round = round(deriv+1)/(deriv+1); m_round = round(matches)/matches
if (p_round!=1 | q_round!=1 | d_round!=1 | m_round!=1 ){
print("p,q,deriv and matches should be integer numbers")
exit = 1
}
if (delta>1 | delta<=0){
print("delta should be set between 0 and 1")
exit = 1
}
if (rho>1 | rho<0){
print("rho should be set between 0 and 1")
exit = 1
}
#if (cvgrid_min<0 | cvgrid_max<0 | cvgrid_length<0 ){
# print("cvgrid_min, cvgrid_max and cvgrid_length should be positive numbers")
# exit = 1
#}
#if (cvgrid_min>cvgrid_max){
# print("cvgrid_min should be lower than cvgrid_max")
# exit = 1
#}
if (exit>0) {
stop()
}
}
if (kernel=="epanechnikov" | kernel=="epa") {
kernel_type = "Epanechnikov"
C_pilot=2.34
}
else if (kernel=="uniform" | kernel=="uni") {
kernel_type = "Uniform"
C_pilot=1.84
}
else {
kernel_type = "Triangular"
C_pilot=2.58
}
p1 = p+1; p2 = p+2; q1 = q+1; q2 = q+2; q3 = q+3
h_CCT=b_CCT=h_IK=b_IK=h_CV=NA
N = length(x)
ct1 = bwconst(p,deriv,kernel)
C1_h = ct1[1]; C2_h = ct1[2]
ct2 = bwconst(q,q,kernel)
C1_b = ct2[1]; C2_b = ct2[2]
ct3 = bwconst(q1,q1,kernel)
C1_q = ct3[1]; C2_q = ct3[2]
#***********************************************************************
#**************************** CCT Approach
#***********************************************************************
if (bwselect=="CCT" | all==TRUE) {
#print("Computing CCT Bandwidth Selector.")
#### Step 1: q_CCT
h_pilot_cct = C_pilot*min(sd(x),IQR(x)/1.349)*N^(-1/5)
X_lq2 = matrix(c((X_l-c)^0, poly(X_l-c, degree = q+2, raw=T)), length(X_l), q+3)
X_rq2 = matrix(c((X_r-c)^0, poly(X_r-c, degree = q+2, raw=T)), length(X_r), q+3)
w_pilot_l = kweight(X_l, c, h_pilot_cct, kernel)
w_pilot_r = kweight(X_r, c, h_pilot_cct, kernel)
Y_pilot_l = Y_l[w_pilot_l>0]; X_pilot_l = X_l[w_pilot_l>0]; w_pilot_l = w_pilot_l[w_pilot_l>0]
Y_pilot_r = Y_r[w_pilot_r>0]; X_pilot_r = X_r[w_pilot_r>0]; w_pilot_r = w_pilot_r[w_pilot_r>0]
sigma_l_pilot = c(rdvce(X = X_pilot_l, y = Y_pilot_l, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
sigma_r_pilot = c(rdvce(X = X_pilot_r, y = Y_pilot_r, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
# V_m3
X_l_pilot_q1 = matrix(c((X_pilot_l-c)^0, poly(X_pilot_l-c, degree = q+1, raw=T)), length(X_pilot_l), q+2)
X_r_pilot_q1 = matrix(c((X_pilot_r-c)^0, poly(X_pilot_r-c, degree = q+1, raw=T)), length(X_pilot_r), q+2)
out.lq1 = qrreg(x = X_l_pilot_q1, y = Y_pilot_l, w = w_pilot_l, s2 = sigma_l_pilot)
out.rq1 = qrreg(x = X_r_pilot_q1, y = Y_pilot_r, w = w_pilot_r, s2 = sigma_r_pilot)
V_m3_pilot_cct = out.lq1$Sigma.hat[q+2,q+2]+ out.rq1$Sigma.hat[q+2,q+2]
# V_m2
X_l_pilot_q = X_l_pilot_q1[,1:(q+1)]; X_r_pilot_q = X_r_pilot_q1[,1:(q+1)]
out.lq = qrreg(x = X_l_pilot_q, y = Y_pilot_l, w = w_pilot_l, s2 = sigma_l_pilot)
out.rq = qrreg(x = X_r_pilot_q, y = Y_pilot_r, w = w_pilot_r, s2 = sigma_r_pilot)
V_m2_pilot_cct = out.lq$Sigma.hat[q+1,q+1] + out.rq$Sigma.hat[q+1,q+1]
# V_m0
X_l_pilot_p = X_l_pilot_q1[,1:(p+1)]; X_r_pilot_p = X_r_pilot_q1[,1:(p+1)]
out.lp = qrreg(x = X_l_pilot_p, y = Y_pilot_l, w = w_pilot_l, s2 = sigma_l_pilot)
out.rp = qrreg(x = X_r_pilot_p, y = Y_pilot_r, w = w_pilot_r, s2 = sigma_r_pilot)
V_m0_pilot_cct = out.lp$Sigma.hat[deriv+1,deriv+1]+ out.rp$Sigma.hat[deriv+1,deriv+1]
# Num/Den
m4_l_pilot_cct = qr.coef(qr(X_lq2, tol = 1e-10), Y_l)[q3]
m4_r_pilot_cct = qr.coef(qr(X_rq2, tol = 1e-10), Y_r)[q3]
D_q_cct = 2*(C1_q*(m4_r_pilot_cct - (-1)^(deriv+q)*m4_l_pilot_cct))^2
N_q_cct = (2*q+3)*N*h_pilot_cct^(2*q+3)*V_m3_pilot_cct
q_CCT = (N_q_cct/(N*D_q_cct))^(1/(2*q+5))
### Step 2: b_CCT
w_q_l=kweight(X_l,c,q_CCT,kernel); w_q_r=kweight(X_r,c,q_CCT,kernel)
Y_q_l = Y_l[w_q_l>0]; Y_q_r = Y_r[w_q_r>0]; X_q_l = X_l[w_q_l>0]; X_q_r = X_r[w_q_r>0]; w_q_l = w_q_l[w_q_l>0]; w_q_r = w_q_r[w_q_r>0]
sigma_l_pilot = c(rdvce(X = X_q_l, y = Y_q_l, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
sigma_r_pilot = c(rdvce(X = X_q_r, y = Y_q_r, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
X_q1_l = matrix(c((X_q_l-c)^0, poly(X_q_l-c, degree = q+1, raw = T)), length(X_q_l), q+2)
X_q1_r = matrix(c((X_q_r-c)^0, poly(X_q_r-c, degree = q+1, raw = T)), length(X_q_r), q+2)
out.lq1 = qrreg(x = X_q1_l, y = Y_q_l, w = w_q_l, s2 = sigma_l_pilot)
out.rq1 = qrreg(x = X_q1_r, y = Y_q_r, w = w_q_r, s2 = sigma_r_pilot)
V_m3_q_cct = out.lq1$Sigma.hat[q+2,q+2]+ out.rq1$Sigma.hat[q+2,q+2]
m3_l_cct = out.lq1$beta[q+2]; m3_r_cct = out.rq1$beta[q+2]
# Num/Den
D_b_cct = 2*(q-p)*(C1_b*(m3_r_cct - (-1)^(deriv+q+1)*m3_l_cct))^2
R_b_cct = scaleregul*2*(q-p)*C1_b^2*3*V_m3_q_cct
N_b_cct = (2*p+3)*N*h_pilot_cct^(2*p+3)*V_m2_pilot_cct
b_CCT = (N_b_cct / (N*(D_b_cct+R_b_cct)))^(1/(2*q+3))
### Step 3: h_CCT
w_b_l = kweight(X_l,c,b_CCT,kernel); w_b_r = kweight(X_r,c,b_CCT,kernel)
Y_b_l=Y_l[w_b_l>0]; Y_b_r=Y_r[w_b_r>0]; X_b_l=X_l[w_b_l>0]; X_b_r=X_r[w_b_r>0];w_b_l=w_b_l[w_b_l>0]; w_b_r=w_b_r[w_b_r>0]
sigma_l_pilot = c(rdvce(X = X_b_l, y = Y_b_l, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
sigma_r_pilot = c(rdvce(X = X_b_r, y = Y_b_r, p = p, h = h_pilot_cct, matches = matches, vce = vce, kernel = kernel))
X_q_l = matrix(c((X_b_l-c)^0, poly(X_b_l-c, degree = q, raw = T)), length(X_b_l), q+1)
X_q_r = matrix(c((X_b_r-c)^0, poly(X_b_r-c, degree = q, raw = T)), length(X_b_r), q+1)
out.lq = qrreg(x = X_q_l, y = Y_b_l, w = w_b_l, s2 = sigma_l_pilot)
out.rq = qrreg(x = X_q_r, y = Y_b_r, w = w_b_r, s2 = sigma_r_pilot)
V_m2_b_cct = out.lq$Sigma.hat[p+2,p+2] + out.rq$Sigma.hat[p+2,p+2]
m2_l_cct = out.lq$beta[p+2]; m2_r_cct=out.rq$beta[p+2]
D_h_cct = 2*(p+1-deriv)*(C1_h*(m2_r_cct - (-1)^(deriv+p+1)*m2_l_cct))^2
R_h_cct = scaleregul*2*(p+1-deriv)*C1_h^2*3*V_m2_b_cct
N_h_cct = (2*deriv+1)*N*h_pilot_cct^(2*deriv+1)*V_m0_pilot_cct
h_CCT = (N_h_cct / (N*(D_h_cct+R_h_cct)))^(1/(2*p+3))
if (b_calc==0) {
b_CCT = h_CCT/rho
}
results = matrix(NA,1,2)
colnames(results)=c("h","b")
rownames(results)=""
results[1,]=c(h_CCT,b_CCT)
}
#***************************************************************************************************
#******************** IK
#**************************************************************************************************
if (bwselect=="IK" | all==TRUE) {
ct2 = bwconst(q,q,"uni")
C1_b_uni = ct2[1]; C2_b_uni = ct2[2]
ct3 = bwconst(q1,q1,"uni")
C1_q_uni = ct3[1]; C2_q_uni = ct3[2]
X_lq2 = matrix(c((X_l-c)^0, poly(X_l-c,degree=(q3-1),raw=T)),length(X_l),q3)
X_rq2 = matrix(c((X_r-c)^0, poly(X_r-c,degree=(q3-1),raw=T)),length(X_r),q3)
X_lq1 = X_lq2[,1:q2]; X_rq1 = X_rq2[,1:q2]
X_lq = X_lq2[,1:q1]; X_rq = X_rq2[,1:q1]
X_lp = X_lq2[,1:p1]; X_rp = X_rq2[,1:p1]
#print("Computing IK Bandwidth Selector.")
h_pilot_IK = 1.84*sd(x)*N^(-1/5)
n_l_h1 = length(X_l[X_l>=c-h_pilot_IK])
n_r_h1 = length(X_r[X_r<=c+h_pilot_IK])
f0_pilot=(n_r_h1+n_l_h1)/(2*N*h_pilot_IK)
s2_l_pilot = var(Y_l[X_l>=c-h_pilot_IK])
s2_r_pilot = var(Y_r[X_r<=c+h_pilot_IK])
if (s2_l_pilot==0){
s2_l_pilot=var(Y_l[X_l>=c-2*h_pilot_IK])
}
if (s2_r_pilot==0){
s2_r_pilot=var(Y_r[X_r<=c+2*h_pilot_IK])
}
V_IK_pilot = (s2_r_pilot+s2_l_pilot)/f0_pilot
Vm0_pilot_IK = C2_h*V_IK_pilot
Vm2_pilot_IK = C2_b*V_IK_pilot
Vm3_pilot_IK = C2_q*V_IK_pilot
x_IK_med_l = X_l[X_l>=median(X_l)]; y_IK_med_l = Y_l[X_l>=median(X_l)]
x_IK_med_r = X_r[X_r<=median(X_r)]; y_IK_med_r = Y_r[X_r<=median(X_r)]
x_IK_med = c(x_IK_med_r,x_IK_med_l); y_IK_med = c(y_IK_med_r,y_IK_med_l)
sample_IK = length(x_IK_med)
X_IK_med_q2 = matrix(c((x_IK_med-c)^0, poly(x_IK_med-c,degree=(q3-1),raw=T)),sample_IK,q3)
X_IK_med_q1 = X_IK_med_q2[,1:q2]
X_IK_med_q2=cbind(X_IK_med_q2,1*(x_IK_med>=c))
X_IK_med_q1=cbind(X_IK_med_q1,1*(x_IK_med>=c))
### First Stage
N_b_IK = (2*p+3)*Vm2_pilot_IK
# Pilot Bandwidth
N_q_r_pilot_IK = (2*q+3)*C2_q_uni*(s2_r_pilot/f0_pilot)
N_q_l_pilot_IK = (2*q+3)*C2_q_uni*(s2_l_pilot/f0_pilot)
m4_pilot_IK = qr.coef(qr(X_IK_med_q2, tol = 1e-10), y_IK_med)[q+3]
D_q_pilot_IK = 2*(C1_q_uni*m4_pilot_IK)^2
h3_r_pilot_IK = (N_q_r_pilot_IK / (N_r*D_q_pilot_IK))^(1/(2*q+5))
h3_l_pilot_IK = (N_q_l_pilot_IK / (N_l*D_q_pilot_IK))^(1/(2*q+5))
# Derivative
X_lq_IK_h3=X_lq1[X_l>=c-h3_l_pilot_IK,]; Y_l_IK_h3 =Y_l[X_l>=c-h3_l_pilot_IK]
X_rq_IK_h3=X_rq1[X_r<=c+h3_r_pilot_IK,]; Y_r_IK_h3 =Y_r[X_r<=c+h3_r_pilot_IK]
m3_l_IK=qr.coef(qr(X_lq_IK_h3, tol = 1e-10), Y_l_IK_h3)[q2]
m3_r_IK=qr.coef(qr(X_rq_IK_h3, tol = 1e-10), Y_r_IK_h3)[q2]
D_b_IK = 2*(q-p)*(C1_b*(m3_r_IK - (-1)^(deriv+q+1)*m3_l_IK))^2
# Regularization
n_l_h3 = length(Y_l_IK_h3);n_r_h3 = length(Y_r_IK_h3)
temp = regconst(q1,1); con = temp[q2,q2]
r_l_b = (con*s2_l_pilot)/(n_l_h3*h3_l_pilot_IK^(2*q1))
r_r_b = (con*s2_r_pilot)/(n_r_h3*h3_r_pilot_IK^(2*q1))
R_b_IK = scaleregul*2*(q-p)*(C1_b)^2*3*(r_l_b + r_r_b)
# Final Bandwidth
b_IK = (N_b_IK / (N*(D_b_IK+R_b_IK)))^(1/(2*q+3))
### Second Stage
N_h_IK = (2*deriv+1)*Vm0_pilot_IK
# Pilot
N_b_r_pilot_IK = (2*p1+1)*C2_b_uni*(s2_r_pilot/f0_pilot)
N_b_l_pilot_IK = (2*p1+1)*C2_b_uni*(s2_l_pilot/f0_pilot)
m3_pilot_IK = qr.coef(qr(X_IK_med_q1, tol = 1e-10), y_IK_med)[q2]
D_b_pilot_IK = 2*(q-p)*(C1_b_uni*m3_pilot_IK)^2
h2_r_pilot_IK = (N_b_r_pilot_IK / (N_r*D_b_pilot_IK))^(1/(2*q+3))
h2_l_pilot_IK = (N_b_l_pilot_IK / (N_l*D_b_pilot_IK))^(1/(2*q+3))
# Derivative
X_lq_IK_h2=X_lq[X_l>=c-h2_l_pilot_IK,]; Y_l_IK_h2 =Y_l[X_l>=c-h2_l_pilot_IK]
X_rq_IK_h2=X_rq[X_r<=c+h2_r_pilot_IK,]; Y_r_IK_h2 =Y_r[X_r<=c+h2_r_pilot_IK]
m2_l_IK=qr.coef(qr(X_lq_IK_h2, tol = 1e-10), Y_l_IK_h2)[p2]
m2_r_IK=qr.coef(qr(X_rq_IK_h2, tol = 1e-10), Y_r_IK_h2)[p2]
D_h_IK = 2*(p+1-deriv)*(C1_h*(m2_r_IK - (-1)^(deriv+p+1)*m2_l_IK))^2
# Regularization
n_l_h2 = length(Y_l_IK_h2);n_r_h2 = length(Y_r_IK_h2)
temp = regconst(p1,1); con = temp[p2,p2]
r_l_h = (con*s2_l_pilot)/(n_l_h2*h2_l_pilot_IK^(2*p1))
r_r_h = (con*s2_r_pilot)/(n_r_h2*h2_r_pilot_IK^(2*p1))
R_h_IK = scaleregul*2*(p+1-deriv)*(C1_h)^2*3*(r_l_h + r_r_h)
# Final Bandwidth
h_IK = (N_h_IK / (N*(D_h_IK+R_h_IK)))^(1/(2*p+3))
#*** DJMC
D_b_DM = 2*(q-p)*C1_b^2*(m3_r_IK^2 + m3_l_IK^2)
D_h_DM = 2*(p+1-deriv)*C1_h^2*(m2_r_IK^2 + m2_l_IK^2)
b_DM = (N_b_IK / (N*D_b_DM))^(1/(2*q+3))
h_DM = (N_h_IK / (N*D_h_DM))^(1/(2*p+3))
if (b_calc==0) {
b_IK = h_IK/rho
}
results = matrix(NA,1,2)
colnames(results)=c("h","b")
#rownames(results)=c("IK")
results[1,]=c(h_IK,b_IK)
}
#*********************************************************************
#********************************** C-V *****************************
#*********************************************************************
if (bwselect=="CV" | all==TRUE) {
#print("Computing CV Bandwidth Selector.")
norep_l=unique(data.frame(X_l,Y_l))
norep_r=unique(data.frame(X_r,Y_r))
X_nr_l = norep_l[,1]; Y_nr_l = norep_l[,2]
X_nr_r = norep_r[,1]; Y_nr_r = norep_r[,2]
N_nr_l = length(X_nr_l);N_nr_r = length(X_nr_r)
v_CV_l = order(X_nr_l,decreasing=FALSE)
x_sort_l = X_nr_l[v_CV_l]
y_sort_l = Y_nr_l[v_CV_l]
v_CV_r = order(X_nr_r,decreasing=TRUE)
x_sort_r = X_nr_r[v_CV_r]
y_sort_r = Y_nr_r[v_CV_r]
h_CV_min = 0
if (N_nr_r>20 & N_nr_l>20){
h_CV_min = min(c(abs(x_sort_r[N_nr_r]-x_sort_r[N_nr_r-20]),abs(x_sort_l[N_nr_l]-x_sort_l[N_nr_l-20])))
}
h_CV_max = min(c(abs(x_sort_r[1]-x_sort_r[N_nr_r]),abs(x_sort_l[1]-x_sort_l[N_nr_l])))
h_CV_jump = min(c(abs(x_sort_r[1]-x_sort_r[N_nr_r])/10,abs(x_sort_l[1]-x_sort_l[N_nr_l]))/10)
if (is.null(cvgrid_min)) {
cvgrid_min = h_CV_min
}
if (is.null(cvgrid_max)) {
cvgrid_max = h_CV_max
}
if (is.null(cvgrid_length)) {
cvgrid_length = abs(cvgrid_max-cvgrid_min)/20
}
if (cvgrid_min>=cvgrid_max){
cvgrid_min = 0
}
h_CV_seq = seq(cvgrid_min, cvgrid_max, cvgrid_length)
s_CV = length(h_CV_seq)
CV_l = CV_r = matrix(0,1,s_CV)
n_CV_l = round(delta*N_nr_l)-3
n_CV_r = round(delta*N_nr_r)-3
# Set quantile sample
for (v in 1:s_CV) {
for (k in 0:n_CV_l) {
ind_l = N_nr_l-k-1
x_CV_sort_l = x_sort_l[1:ind_l];y_CV_sort_l = y_sort_l[1:ind_l]
w_CV_sort_l = kweight(x_CV_sort_l,x_sort_l[ind_l+1],h_CV_seq[v],kernel)
x_CV_l = x_CV_sort_l[w_CV_sort_l>0];y_CV_l = y_CV_sort_l[w_CV_sort_l>0];w_CV_l = w_CV_sort_l[w_CV_sort_l>0]
XX_CV_l = matrix(c((x_CV_l-x_sort_l[ind_l+1])^0, poly(x_CV_l-x_sort_l[ind_l+1],degree=p,raw=T)),length(w_CV_l),p+1)
y_CV_hat_l = qr.coef(qr(XX_CV_l*sqrt(w_CV_l), tol = 1e-10), sqrt(w_CV_l)*y_CV_l)[1]
mse_CV_l = (y_sort_l[ind_l+1] - y_CV_hat_l)^2
CV_l[v] = CV_l[v] + mse_CV_l
}
for (k in 0:n_CV_r) {
ind_r = N_nr_r-k-1
x_CV_sort_r = x_sort_r[1:ind_r];y_CV_sort_r = y_sort_r[1:ind_r]
w_CV_sort_r = kweight(x_CV_sort_r,x_sort_r[ind_r+1],h_CV_seq[v],kernel)
x_CV_r = x_CV_sort_r[w_CV_sort_r>0];y_CV_r = y_CV_sort_r[w_CV_sort_r>0];w_CV_r = w_CV_sort_r[w_CV_sort_r>0]
XX_CV_r = matrix(c((x_CV_r - x_sort_r[ind_r+1])^0, poly(x_CV_r-x_sort_r[ind_r+1],degree=p,raw=T)),length(w_CV_r),p+1)
y_CV_hat_r = qr.coef(qr(XX_CV_r*sqrt(w_CV_r), tol = 1e-10), sqrt(w_CV_r)*y_CV_r)[1]
mse_CV_r = (y_sort_r[ind_r+1] - y_CV_hat_r)^2
CV_r[v] = CV_r[v] + mse_CV_r
}
}
CV_sum = CV_l + CV_r
CV_sum_order = order(abs(t(CV_sum)))[1]
h_CV = h_CV_seq[CV_sum_order]
h_CV = h_CV[1]
if (cvplot==TRUE){
plot(h_CV_seq,CV_sum, type="l",main="Cross-Validation Objective Function",xlab="Grid of Bandwidth (h)",ylab="Cross-Validation Objective Function")
abline(v=h_CV)
}
#if (b_calc==0) {
# b_CV = h_CV/rho
#}
results = matrix(NA,1,2)
colnames(results)=c("h","b")
#rownames(results)=c("CV")
results[1,]=c(h_CV,h_CV/rho)
}
#results=list(CCT=c(h_CCT,b_CCT),IK=c(h_IK,b_IK),CV=h_CV)
if (all=="TRUE"){
bwselect="All"
results = matrix(NA,3,2)
colnames(results)=c("h","b")
rownames(results)=c("CCT","IK","CV")
results[1,]=c(h_CCT,b_CCT)
results[2,]=c(h_IK,b_IK)
results[3,1]=h_CV
#results[4,]=c(h_DM,b_DM)
}
tabl1.str=matrix(NA,4,1)
dimnames(tabl1.str) <-list(c("BW Selector", "Number of Obs", "NN Matches", "Kernel Type"), rep("", dim(tabl1.str)[2]))
tabl1.str[1,1]=bwselect
tabl1.str[2,1]=N
tabl1.str[3,1]=matches
tabl1.str[4,1]=kernel_type
tabl2.str=matrix(NA,3,2)
colnames(tabl2.str)=c("Left","Right")
rownames(tabl2.str)=c("Number of Obs","Order Loc Poly (p)","Order Bias (q)")
tabl2.str[1,]=formatC(c(N_l,N_r),digits=0, format="f")
tabl2.str[2,]=formatC(c(p,p),digits=0, format="f")
tabl2.str[3,]=formatC(c(q,q),digits=0, format="f")
bws=results
out = list(tabl1.str=tabl1.str,tabl2.str=tabl2.str,bws=bws,bws,bwselect=bwselect,kernel=kernel_type,p=p,q=q)
out$call <- match.call()
class(out) <- "rdbwselect"
return(out)
}
#rdbwselect <- function(y,x, ...) UseMethod("rdbwselect")
#rdbwselect.default <- function(y,x, ...){
# est <- rdbwselectEst(y,x, ...)
# est$call <- match.call()
# class(est) <- "rdbwselect"
# est
#}
print.rdbwselect <- function(x,...){
cat("Call:\n")
print(x$call)
print(x$tabl1.str,quote=F)
cat("\n")
print(x$tabl2.str,quote=F)
cat("\n")
print(x$bws)
}
summary.rdbwselect <- function(object,...) {
TAB <- object$bws
res <- list(call=object$call, coefficients=TAB)
class(res) <- "summary.rdbwselect"
res
}
#print.summary.rdbwselect <- function(x, ...){
# cat("Call:\n")
# print(x$call)
# cat("\n")
# printCoefmat(x$coefficients, P.values=FALSE, has.Pvalue=FALSE)
#}
### Copyright (c) Sebastian Calonico <scalonico@bus.miami.edu>,
### Matias D. Cattaneo <cattaneo@umich.edu>,
### Rocio Titiunik <titiunik@umich.edu>
###
### This file is part of the rdrobust R package.
###
### Rdrobust is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, version 2 of the License.
###
### Rdrobust is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with rdrobust. If not, see <http://www.gnu.org/licenses/>.
### version 0.1 18Nov2013
### version 0.2 26Nov2013
### version 0.3 21Abr2014
### version 0.5 06Jun2014
### version 0.6 17Jun2014
### version 0.61 03Sep2014
### version 0.7 14Oct2014
### version 0.8 04Feb2015
rdplot = function(y, x, subset = NULL, c=0, p=4, numbinl=NULL, numbinr=NULL,
binselect="esmv", lowerend=NULL, upperend=NULL, scale=1, scalel=1,scaler=1,
hide=FALSE, par=NULL, title=NULL, x.label=NULL, y.label=NULL,
x.lim=NULL, y.lim=NULL, col.dots=NULL, col.lines=NULL, type.dots = NULL,...) {
call <- match.call()
#if (missing(data))
#data <- environment(formula)
if (!is.null(subset)) {
x <- x[subset]
y <- y[subset]
}
na.ok <- complete.cases(x) & complete.cases(y)
x <- x[na.ok]
y <- y[na.ok]
#if (frame) {
# dat.out <- data.frame(x, y)
#}
if (is.null(lowerend)) {
lowerend = min(x)
}
if (is.null(upperend)) {
upperend = max(x)
}
x_low = lowerend
x_upp = upperend
if (is.null(col.lines)) {
col.lines="blue"
}
if (is.null(col.dots)) {
col.dots=1
}
if (is.null(type.dots)) {
type.dots=20
}
size=sum(x>=x_low & x<=x_upp)
y=y[x>=x_low & x<=x_upp]
x=x[x>=x_low & x<=x_upp]
x_l = x[x<c]; x_r = x[x>=c]
y_l = y[x<c]; y_r = y[x>=c]
x.min = min(x); x.max = max(x)
range_l = max(x_l) - min(x_l)
n_l = length(x_l)
range_r = max(x_r) - min(x_r)
n_r = length(x_r)
n = n_l + n_r
meth="es"
#####********************* ERRORS
exit=0
if (c<=x.min | c>=x.max){
print("c should be set within the range of x")
exit = 1
}
if (p<=0 ){
print("p should be a positive number")
exit = 1
}
if (scale<=0 |scalel<=0 |scaler<=0){
print("scale should be a positive number")
exit = 1
}
p_ceiling = ceiling(p)/p
if (p_ceiling!=1) {
print("p should be an integer number")
exit = 1
}
if (exit>0) {
stop()
}
p1 = p+1
compute =0
rp_l = matrix(NA,n_l,p+1); rp_r = matrix(NA,n_r,p+1)
for (j in 1:p1) {
rp_l[,j] = x_l^(j-1)
rp_r[,j] = x_r^(j-1)
}
gamma_p1_l = lm(y_l~rp_l-1)$coeff
gamma_p1_r = lm(y_r~rp_r-1)$coeff
mu0_p1_l = rp_l%*%gamma_p1_l; mu0_p1_r = rp_r%*%gamma_p1_r
J_star_orig=c(numbinl, numbinr)
y_l.sq = y_l^2
y_r.sq = y_r^2
gamma_p2_l = lm(y_l.sq~rp_l-1)$coeff
gamma_p2_r = lm(y_r.sq~rp_r-1)$coeff
### Bias w/sample
drp_l = matrix(NA,n_l,p); drp_r = matrix(NA,n_r,p)
for (j in 1:p) {
drp_l[,j] = j*x_l^(j-1)
drp_r[,j] = j*x_r^(j-1)
}
mu1_hat_l = drp_l%*%(gamma_p1_l[2:p1])
mu1_hat_r = drp_r%*%(gamma_p1_r[2:p1])
######################### ES
ind.l = order(x_l); ind.r = order(x_r)
x.i.l = x_l[ind.l]; x.i.r = x_r[ind.r]
y.i.l = y_l[ind.l]; y.i.r = y_r[ind.r]
dxi.l=(x.i.l[2:length(x.i.l)]-x.i.l[1:(length(x.i.l)-1)])
dxi.r=(x.i.r[2:length(x.i.r)]-x.i.r[1:(length(x.i.r)-1)])
dyi.l=(y.i.l[2:length(y.i.l)]-y.i.l[1:(length(y.i.l)-1)])
dyi.r=(y.i.r[2:length(y.i.r)]-y.i.r[1:(length(y.i.r)-1)])
x.bar.i.l = (x.i.l[2:length(x.i.l)]+x.i.l[1:(length(x.i.l)-1)])/2
x.bar.i.r = (x.i.r[2:length(x.i.r)]+x.i.r[1:(length(x.i.r)-1)])/2
rp.i_l = matrix(NA,n_l-1,p+1); rp.i_r= matrix(NA,n_r-1,p+1)
drp.i_l = matrix(NA,n_l-1,p); drp.i_r = matrix(NA,n_r-1,p)
for (j in 1:p1) {
rp.i_l[,j] = x.bar.i.l^(j-1)
rp.i_r[,j] = x.bar.i.r^(j-1)
}
for (j in 1:p) {
drp.i_l[,j] = j*x.bar.i.l^(j-1)
drp.i_r[,j] = j*x.bar.i.r^(j-1)
}
mu0.i_hat_l = rp.i_l%*%gamma_p1_l; mu0.i_hat_r = rp.i_r%*%gamma_p1_r
mu2.i_hat_l = rp.i_l%*%gamma_p2_l; mu2.i_hat_r = rp.i_r%*%gamma_p2_r
mu0_hat_l = rp_l%*%gamma_p1_l; mu0_hat_r = rp_r%*%gamma_p1_r
mu2_hat_l = rp_l%*%gamma_p2_l; mu2_hat_r = rp_r%*%gamma_p2_r
mu1.i_hat_l = drp.i_l%*%(gamma_p1_l[2:p1]); mu1.i_hat_r = drp.i_r%*%(gamma_p1_r[2:p1])
sigma2_hat_l.bar = mu2.i_hat_l - mu0.i_hat_l^2
sigma2_hat_r.bar = mu2.i_hat_r - mu0.i_hat_r^2
sigma2_hat_l = mu2_hat_l - mu0_hat_l^2
sigma2_hat_r = mu2_hat_r - mu0_hat_r^2
J.fun = function(B,V) {ceiling((((2*B)/V)*n)^(1/3))}
var.y_l = var(y_l)
var.y_r = var(y_r)
B.es.hat.dw = c( ((c-x.min)^2/(12*n))*sum(mu1_hat_l^2),((x.max-c)^2/(12*n))*sum(mu1_hat_r^2))
V.es.hat.dw = c((0.5/(c-x.min))*sum(dxi.l*dyi.l^2),(0.5/(x.max-c))*sum(dxi.r*dyi.r^2))
V.es.chk.dw = c((1/(c-x.min))*sum(dxi.l*sigma2_hat_l.bar),(1/(x.max-c))*sum(dxi.r*sigma2_hat_r.bar))
J.es.hat.dw = J.fun(B.es.hat.dw, V.es.hat.dw)
J.es.chk.dw = J.fun(B.es.hat.dw, V.es.chk.dw)
B.qs.hat.dw = c((n_l^2/(24*n))*sum(dxi.l^2*mu1.i_hat_l^2), (n_r^2/(24*n))*sum(dxi.r^2*mu1.i_hat_r^2))
V.qs.hat.dw = c((1/(2*n_l))*sum(dyi.l^2),(1/(2*n_r))*sum(dyi.r^2))
V.qs.chk.dw = c((1/n_l)*sum(sigma2_hat_l), (1/n_r)*sum(sigma2_hat_r))
J.qs.hat.dw = J.fun(B.qs.hat.dw, V.qs.hat.dw)
J.qs.chk.dw = J.fun(B.qs.hat.dw, V.qs.chk.dw)
J.es.hat.mv = c(ceiling((var.y_l/V.es.hat.dw[1])*(n/log(n)^2)), ceiling((var.y_r/V.es.hat.dw[2])*(n/log(n)^2)))
J.es.chk.mv = c(ceiling((var.y_l/V.es.chk.dw[1])*(n/log(n)^2)), ceiling((var.y_r/V.es.chk.dw[2])*(n/log(n)^2)))
J.qs.hat.mv = c(ceiling((var.y_l/V.qs.hat.dw[1])*(n/log(n)^2)), ceiling((var.y_r/V.qs.hat.dw[2])*(n/log(n)^2)))
J.qs.chk.mv = c(ceiling((var.y_l/V.qs.chk.dw[1])*(n/log(n)^2)), ceiling((var.y_r/V.qs.chk.dw[2])*(n/log(n)^2)))
######################### ES
#var2.y_l = IQR(y_l) / 1.349
#var2.y_r = IQR(y_r) / 1.349
#B.es.hat = c(((c-x.min)^2/12)*sum(dxi.l*mu1.i_hat_l^2), ((x.max-c)^2/12)*sum(dxi.r*mu1.i_hat_r^2))
#V.es.hat = c((n/(4*(c-x.min)))*sum(dxi.l^2*dyi.l^2), (n/(4*(x.max-c)))*sum(dxi.r^2*dyi.r^2))
#J.es.hat = J.fun(B.es.hat,V.es.hat)
#B.es.hat.dw = c( ((c-x.min)^2/(12*n))*sum(mu1.i_hat_l^2),((x.max-c)^2/(12*n))*sum(mu1.i_hat_r^2))
#V.es.chk = c((n/(2*(c-x.min)))*sum(dxi.l^2*sigma2_hat_l.bar),(n/(2*(x.max-c)))*sum(dxi.r^2*sigma2_hat_r.bar))
#J.es.chk = J.fun(B.es.hat,V.es.chk)
######################### QS
#V.qs.hat = c((n/(2*n_l))*sum(dxi.l*dyi.l^2),(n/(2*n_r))*sum(dxi.r*dyi.r^2))
#B.qs.hat = c((n_l^2/72)*sum(dxi.l^3*mu1.i_hat_l^2), (n_r^2/72)*sum(dxi.r^3*mu1.i_hat_r^2))
#J.qs.hat = J.fun(B.qs.hat,V.qs.hat)
#V.qs.chk = c((n/n_l)*sum(dxi.l*sigma2_hat_l.bar),(n/n_r)*sum(dxi.r*sigma2_hat_r.bar))
#J.qs.chk = J.fun(B.qs.hat,V.qs.chk)
#B.qs.hat.dw = c((n_l^1/48)*sum(dxi.l^2*mu1.i_hat_l^2), (n_r^1/48)*sum(dxi.r^2*mu1.i_hat_r^2))
if (binselect=="es") {
J_star_orig = J.es.hat.dw
meth="es"
binselect_type="IMSE-optimal evenly-spaced method using spacings estimators"
J_IMSE = J.es.hat.dw
J_MV = J.es.hat.mv
}
if (binselect=="espr") {
J_star_orig = J.es.chk.dw
meth="es"
binselect_type="IMSE-optimal evenly-spaced method using polynomial regression"
J_IMSE = J.es.chk.dw
J_MV = J.es.chk.mv
}
if (binselect=="esmv" ) {
J_star_orig = J.es.hat.mv
meth="es"
binselect_type="mimicking variance evenly-spaced method using spacings estimators"
J_IMSE = J.es.hat.dw
J_MV = J.es.hat.mv
}
if (binselect=="esmvpr" ) {
J_star_orig = J.es.chk.mv
meth="es"
binselect_type="mimicking variance evenly-spaced method using polynomial regression"
J_IMSE = J.es.chk.dw
J_MV = J.es.chk.mv
}
if (binselect=="qs" ) {
J_star_orig = J.qs.hat.dw
meth="qs"
binselect_type="IMSE-optimal quantile-spaced method using spacings estimators"
J_IMSE = J.qs.hat.dw
J_MV = J.qs.hat.mv
}
if (binselect=="qspr" ) {
J_star_orig = J.qs.chk.dw
meth="qs"
binselect_type="IMSE-optimal quantile-spaced method using polynomial regression"
J_IMSE = J.qs.chk.dw
J_MV = J.qs.chk.mv
}
if (binselect=="qsmv" ) {
J_star_orig = J.qs.hat.mv
meth="qs"
binselect_type="mimicking variance quantile-spaced method using spacings estimators"
J_IMSE = J.qs.hat.dw
J_MV = J.qs.hat.mv
}
if (binselect=="qsmvpr" ) {
J_star_orig = J.qs.chk.mv
meth="qs"
binselect_type="mimicking variance quantile-spaced method using polynomial regression"
J_IMSE = J.qs.chk.dw
J_MV = J.qs.chk.mv
}
if (scale>1 & scalel==1 & scaler==1){
scalel=scaler=scale
}
J_star_l = scalel*J_star_orig[1]
J_star_r = scaler*J_star_orig[2]
if (!is.null(numbinl)&!is.null(numbinr)) {
J_star_l = numbinl
J_star_r = numbinr
binselect_type="manually evenly spaced"
}
scale_l = J_star_l / J_IMSE[1]
scale_r = J_star_r / J_IMSE[2]
bin_x_l = rep(0,length(x_l)); bin_x_r = rep(0,length(x_r))
jump_l = range_l/J_star_l;jump_r = range_r/J_star_r;
if (meth=="es") {
jumps_l=seq(min(x_l),max(x_l),jump_l)
jumps_r=seq(min(x_r),max(x_r),jump_r)
#binselect_type="Evenly-Spaced"
}
else if (meth=="qs") {
jumps_l=quantile(x_l,probs=seq(0,1,1/J_star_l))
jumps_r=quantile(x_r,probs=seq(0,1,1/J_star_r))
# binselect_type="Quantile-Spaced"
}
for (k in 1:(J_star_l-1)) {
bin_x_l[x_l>=jumps_l[k] & x_l<jumps_l[k+1]] = -J_star_l+k-1
}
bin_x_l[x_l>=jumps_l[(J_star_l)]] = -1
for (k in 1:(J_star_r-1)) {
bin_x_r[x_r>=jumps_r[k] & x_r<jumps_r[k+1]] = k
}
bin_x_r[x_r>=jumps_r[(J_star_r)]] = J_star_r
bin_xlmean=bin_ylmean=rep(0,J_star_l)
bin_xrmean=bin_yrmean=rep(0,J_star_r)
for (k in 1:(J_star_l)) {
bin_xlmean[k]=mean(c(jumps_l[k],jumps_l[k+1]))
#bin_xlmean[k]=mean(x_l[bin_x_l==-k])
bin_ylmean[J_star_l-k+1]=mean(y_l[bin_x_l==-k])
}
for (k in 1:(J_star_r)) {
bin_xrmean[k]=mean(c(jumps_r[k],jumps_r[k+1]))
#bin_xrmean[k]=mean(x_r[bin_x_r==k])
bin_yrmean[k]=mean(y_r[bin_x_r==k])
}
bin_x=c(bin_x_l,bin_x_r)
bin_xmean=c(bin_xlmean,bin_xrmean)
bin_ymean=c(bin_ylmean,bin_yrmean)
x_sup = c(x_l, x_r)
#y_hat = c(mu0_p1_l, mu0_p1_r)
if (hide=="FALSE") {
if (is.null(title)){
title="RD Plot"
}
if (is.null(x.label)){
x.label="X axis"
}
if (is.null(y.label)){
y.label="Y axis"
}
if (is.null(x.lim)){
x.lim=c(min(x_l),max(x_r))
}
if (is.null(y.lim)){
y.lim=c(min(c(y_l,y_r)),max(c(y_l,y_r)))
}
par=par
plot(bin_xmean[order(bin_xmean)],bin_ymean[order(bin_xmean)], main=title, xlab=x.label, ylab=y.label, ylim=y.lim, xlim=x.lim, col=col.dots, pch=type.dots,...)
#points(x_l[order(x_l)],mu0_p1_l[order(x_l)],type="l",col=2)
#points(x_r[order(x_r)],mu0_p1_r[order(x_r)],type="l",col=2)
lines(x_l[order(x_l)],mu0_p1_l[order(x_l)],type="l",col=col.lines)
lines(x_r[order(x_r)],mu0_p1_r[order(x_r)],type="l",col=col.lines)
abline(v=c)
}
# if (compute==1) {
tabl1.str=matrix(NA,14,2)
tabl1.str[1,] = formatC(c(n_l,n_r),digits=0, format="f")
tabl1.str[2,] = formatC(c(p,p),digits=0, format="f")
tabl1.str[3,] = formatC(c(scalel,scaler),digits=0, format="f")
tabl1.str[4,] = c("","")
tabl1.str[5,] = formatC(c(J_star_l,J_star_r),digits=0, format="f")
tabl1.str[6,] = formatC(c(jump_l,jump_r),digits=4, format="f")
tabl1.str[7,] = c("","")
tabl1.str[8,] = formatC(c(J_IMSE),digits=0, format="f")
tabl1.str[9,] = formatC(c(J_MV),digits=0, format="f")
tabl1.str[10,] = c("","")
tabl1.str[11,] = c("","")
tabl1.str[12,] = formatC(c(scale_l,scale_r),digits=4, format="f")
tabl1.str[13,] = formatC(c(1/(1+scale_l^3), 1/(1+scale_r^3)),digits=4, format="f")
tabl1.str[14,] = formatC(c(scale_l^3/(1+scale_l^3), scale_r^3/(1+scale_r^3)),digits=4, format="f")
rownames(tabl1.str)=c("Number of Obs.","Polynomial Order","Scale", "","Selected Bins","Bin Length","", "IMSE-optimal bins","Mimicking Variance bins","","Relative to IMSE-optimal:","Implied scale","WIMSE variance weight","WIMSE bias weight")
colnames(tabl1.str)=c("Left","Right")
results=matrix(NA,10,2)
results[1,] = c(n_l,n_r)
results[2,] = c(p,p)
results[3,] = c(scalel,scaler)
results[4,] = c(J_star_l,J_star_r)
results[5,] = c(jump_l,jump_r)
results[6,] = J_IMSE
results[7,] = J_MV
results[8,] = c(scale_l,scale_r)
results[9,] = c(1/(1+scale_l^3), 1/(1+scale_r^3))
results[10,] = c(scale_l^3/(1+scale_l^3), scale_r^3/(1+scale_r^3))
rownames(results)=c("Number of Obs.","Polynomial Order","Chosen Scale","Selected bins","Bin Length","IMSE-optimal bins","Mimicking Variance bins","Implied scale","WIMSE variance weight","WIMSE bias weight")
colnames(results)=c("Left","Right")
coef=matrix(NA,p+1,2)
coef[,1] = c(gamma_p1_l)
coef[,2] = c(gamma_p1_r)
colnames(coef)=c("Left","Right")
out=list(method=binselect_type,results=results,coef=coef,tabl1.str=tabl1.str)
out$call <- match.call()
class(out) <- "rdplot"
return(invisible(out))
# }
}
#rdplot <- function(y,x, ...) UseMethod("rdplot")
#rdplot.default <- function(y,x, ...){
# est <- rdplotEst(y,x, ... )
# est$call <- match.call()
# class(est) <- "rdplot"
# est
#}
print.rdplot <- function(x,...){
cat("Call:\n")
#print(x$call)
cat(deparse(x$call, width.cutoff=getOption("width")), sep = "\n")
cat("\n")
#cat(paste("Method: ",x$method))
cat(strwrap(paste("Method: ", x$method)), sep = "\n")
cat("\n\n")
print(x$tabl1.str,quote=F)
}
summary.rdplot <- function(object,...) {
TAB <- object$results
res <- list(call=object$call, coefficients=TAB)
class(res) <- "summary.rdplot"
res
}
#print.summary.rdplot <- function(x, ...){
# cat("Call:\n")
# print(x$call)
# cat("\n")
# printCoefmat(x$coefficients, P.values=FALSE, has.Pvalue=FALSE)
#}
### Copyright (c) Sebastian Calonico <scalonico@bus.miami.edu>,
### Matias D. Cattaneo <cattaneo@umich.edu>,
### Rocio Titiunik <titiunik@umich.edu>
###
### This file is part of the rdrobust R package.
###
### Rdrobust is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, version 2 of the License.
###
### Rdrobust is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with rdrobust. If not, see <http://www.gnu.org/licenses/>.
Package: rdrobust
Type: Package
Title: Robust Data-Driven Statistical Inference in
Regression-Discontinuity Designs
Version: 0.80
Date: 2015-03-18
Author: Sebastian Calonico <scalonico@bus.miami.edu>, Matias D. Cattaneo <cattaneo@umich.edu>, Rocio Titiunik <titiunik@umich.edu>
Maintainer: Sebastian Calonico <scalonico@bus.miami.edu>
Description: Regression-discontinuity (RD) designs are quasi-experimental research designs popular in social, behavioral and natural sciences. The RD design is usually employed to study the (local) causal effect of a treatment, intervention or policy. This package provides tools for data-driven graphical and analytical statistical inference in RD designs: rdrobust to construct local-polynomial point estimators and robust confidence intervals for average treatment effects at the cutoff in Sharp, Fuzzy and Kink RD settings, rdbwselect to perform bandwidth selection for the different procedures implemented, and rdplot to conduct exploratory data analysis (RD plots).
Depends: R (>= 3.0.2)
License: GPL-2
Packaged: 2015-03-19 13:40:00 UTC; Home
NeedsCompilation: no
Repository: CRAN
Date/Publication: 2015-03-19 23:51:17
### version 0.1 18Nov2013
### version 0.2 26Nov2013
### version 0.3 21Abr2014
### version 0.5 06Jun2014
### version 0.6 17Jun2014
### version 0.61 03Sep2014
### version 0.7 14Oct2014
### version 0.8 04Feb2015
rdrobust = function(y, x, subset = NULL, c=0, p=1, q=2, deriv=0, fuzzy=NULL, h=NULL, b=NULL, rho=NULL, scalepar=1, kernel="tri", bwselect="CCT", scaleregul=1, delta=0.5, cvgrid_min=NULL, cvgrid_max=NULL, cvgrid_length=NULL, cvplot=FALSE, vce="nn", matches=3, level=95, all=FALSE) {
call <- match.call()
#if (missing(data))
#data <- environment(formula)
if (!is.null(subset)) {
x <- x[subset]
y <- y[subset]
}
na.ok <- complete.cases(x) & complete.cases(y)
if (!is.null(fuzzy)){
type <- "fuzzy"
z=fuzzy
if (!is.null(subset))
z <- z[subset]
na.ok <- na.ok & complete.cases(z)
}
else {
type <- "sharp"
}
x <- x[na.ok]
y <- y[na.ok]
if (type == "fuzzy")
z <- as.double(z[na.ok])
#if (frame) {
# if (type == "sharp") {
# dat.out <- data.frame(x, y)
# }
# else {
# dat.out <- data.frame(x, y, z)
# }
#}
kernel = tolower(kernel)
bwselect = toupper(bwselect)
vce = tolower(vce)
X_l=x[x<c]; X_r=x[x>=c]
Y_l=y[x<c]; Y_r=y[x>=c]
x_min = min(x); x_max = max(x)
N_l = length(X_l); N_r = length(X_r)
range_l = abs(max(X_l)-min(X_l)); range_r = abs(max(X_r)-min(X_r))
N = N_r + N_l
m = matches + 1
quant = -qnorm(abs((1-(level/100))/2))
#if (deriv==0 & p==0){
# p = 1
#}
#if (deriv>0 & p==0){
# bwselect = "CCT"
# p = deriv+1
#}
if (q==0) {
q = p+1
}
p1 = p+1; q1 = q+1; exit = 0
##################################################### CHECK ERRORS
if (kernel!="uni" & kernel!="uniform" & kernel!="tri" & kernel!="triangular" & kernel!="epa" & kernel!="epanechnikov" & kernel!="" ){
print("kernel incorrectly specified")
exit = 1
}
if (bwselect!="CCT" & bwselect!="IK" & bwselect!="CV" & bwselect!=""){
print("bwselect incorrectly specified")
exit = 1
}
if (vce!="resid" & vce!="nn" & vce!="" & vce!="s2.pob"){
print("vce incorrectly specified")
exit = 1
}
if (c<=x_min | c>=x_max){
print("c should be set within the range of x")
exit = 1
}
if (p<=0 | q<=0 | deriv<0 | matches<=0 ){
print("p,q,deriv and matches should be positive integers")
exit = 1
}
if (p>=q & q>0){
print("p should be set higher than q")
exit = 1
}
if (deriv>p & deriv>0 ){
print("deriv should be set higher than p")
exit = 1
}
p_round = round(p)/p; q_round = round(q)/q; d_round = round(deriv+1)/(deriv+1); m_round = round(matches)/matches
if (p_round!=1 | q_round!=1 | d_round!=1 | m_round!=1 ){
print("p,q,deriv and matches should be integer numbers")
exit = 1
}
if (delta>1 | delta<=0){
print("delta should be set between 0 and 1")
exit = 1
}
if (level>100 | level<=0){
print("level should be set between 0 and 100")
exit = 1
}
if (!is.null(rho)){
if (rho<0){
print("rho should be greater than 0")
exit = 1
}
}
#if (cvgrid_min<0 | cvgrid_max<0 | cvgrid_length<0 ){
# print("cvgrid_min, cvgrid_max and cvgrid_length should be positive numbers")
# exit = 1
#}
#if (cvgrid_min>cvgrid_max){
# print("cvgrid_min should be lower than cvgrid_max")
# exit = 1
#}
if (exit>0) {
stop()
}
if (!is.null(h)) {
bwselect = "Manual"
}
if (!is.null(h) & is.null(rho) & is.null(b)) {
rho = 1
b = h
}
if (!is.null(h) & !is.null(rho) ) {
b = h/rho
}
############################################################################################
#print("Preparing data.")
if (is.null(h) & bwselect=="IK") {
rdbws=rdbwselect(y=y, x=x, c=c, rho=rho, p=p, q=q, bwselect="IK", kernel=kernel, precalc=FALSE, scaleregul=scaleregul)
h = rdbws$bws[1,1]; b = rdbws$bws[1,2]
bwselect = "IK"
}
else if (is.null(h) & bwselect=="CV") {
rdbws=rdbwselect(y=y, x=x, c=c, rho=rho, p=p, q=q, bwselect="CV", kernel=kernel, precalc=FALSE, delta=delta, cvgrid_min=cvgrid_min, cvgrid_max=cvgrid_max, cvgrid_length=cvgrid_length, scaleregul=scaleregul)
h = rdbws$bws[1,1]; b = rdbws$bws[1,2]
bwselect = "CV"
}
else if (is.null(h)) {
rdbws=rdbwselect(y=y, x=x, c=c, rho=rho, p=p, q=q, bwselect="CCT", kernel=kernel, precalc=FALSE, matches=matches, vce=vce, scaleregul=scaleregul, deriv=deriv)
h = rdbws$bws[1,1]; b = rdbws$bws[1,2]
bwselect = "CCT"
}
if (kernel=="epanechnikov" | kernel=="epa") {
kernel_type = "Epanechnikov"
}
else if (kernel=="uniform" | kernel=="uni") {
kernel_type = "Uniform"
}
else {
kernel_type = "Triangular"
}
N_l = length(X_l); N_r = length(X_r)
wh_l = kweight(X_l,c,h,kernel); wh_r = kweight(X_r,c,h,kernel);
wb_l = kweight(X_l,c,b,kernel); wb_r = kweight(X_r,c,b,kernel)
uh_l = (X_l-c)/h; uh_r = (X_r-c)/h; uhh_l=uh_l[wh_l>0]; uhh_r=uh_r[wh_r>0]
Yh_l = Y_l[wh_l>0]; Yh_r = Y_r[wh_r>0]; Yb_l = Y_l[wb_l>0]; Yb_r = Y_r[wb_r>0]
Xh_l = X_l[wh_l>0]; Xh_r = X_r[wh_r>0]; Xb_l = X_l[wb_l>0]; Xb_r = X_r[wb_r>0]
whh_l = wh_l[wh_l>0]; whh_r = wh_r[wh_r>0]; wbb_l = wb_l[wb_l>0]; wbb_r = wb_r[wb_r>0]
if (type == "fuzzy") {
T_l = matrix(z[x<c]); T_r = matrix(z[x>=c])
Th_l = matrix(T_l[wh_l>0]); Th_r = matrix(T_r[wh_r>0])
Tb_l = matrix(T_l[wb_l>0]); Tb_r = matrix(T_r[wb_r>0])
}
Nh_l = length(Xh_l); Nb_l = length(Xb_l); Nh_r = length(Xh_r); Nb_r = length(Xb_r)
if (Nh_l<5 | Nh_r<5 | Nb_l<5 | Nb_r<5){
stop("Too few observations to compute RD estimates")
}
X_lp = matrix(c((X_l-c)^0, poly(X_l-c,degree=p,raw=T)),length(X_l),p+1)
X_rp = matrix(c((X_r-c)^0, poly(X_r-c,degree=p,raw=T)),length(X_r),p+1)
Xh_lp = matrix(c((Xh_l-c)^0,poly(Xh_l-c,degree=p,raw=T)),length(Xh_l),p+1)
Xh_rp = matrix(c((Xh_r-c)^0,poly(Xh_r-c,degree=p,raw=T)),length(Xh_r),p+1)
X_lq = matrix(c((X_l-c)^0, poly(X_l-c,degree=q,raw=T)),length(X_l),q+1)
X_rq = matrix(c((X_r-c)^0, poly(X_r-c,degree=q,raw=T)),length(X_r),q+1)
Xb_lq = matrix(c((Xb_l-c)^0,poly(Xb_l-c,degree=q,raw=T)),length(Xb_l),q+1)
Xb_rq = matrix(c((Xb_r-c)^0,poly(Xb_r-c,degree=q,raw=T)),length(Xb_r),q+1)
#print("Computing Variance-Covariance Matrix.")
sigmah_l = c(rdvce(X=Xh_l, y=Yh_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmah_r = c(rdvce(X=Xh_r, y=Yh_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_l = c(rdvce(X=Xb_l, y=Yb_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_r = c(rdvce(X=Xb_r, y=Yb_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
#print("Computing RD Estimates.")
factor_p = factorial(seq(0,p,1))
factor_q = factorial(seq(0,q,1))
out.lp=qrreg(Xh_lp,Yh_l,whh_l,sigmah_l)
out.rp=qrreg(Xh_rp,Yh_r,whh_r,sigmah_r)
out.lq=qrreg(Xb_lq,Yb_l,wbb_l,sigmab_l)
out.rq=qrreg(Xb_rq,Yb_r,wbb_r,sigmab_r)
tau_lp = factor_p*out.lp$beta.hat
tau_rp = factor_p*out.rp$beta.hat
tau_lq = factor_q*out.lq$beta.hat
tau_rq = factor_q*out.rq$beta.hat
V_lp = out.lp$Sigma.hat
V_rp = out.rp$Sigma.hat
V_lq = out.lq$Sigma.hat
V_rq = out.rq$Sigma.hat
invGamma_lp = out.lp$X.M.X_inv
invGamma_rp = out.rp$X.M.X_inv
invGamma_lq = out.lq$X.M.X_inv
invGamma_rq = out.rq$X.M.X_inv
if (b>=h){
whb_l = wh_l[wb_l>0]; Xb_lp = X_lp[wb_l>0,]
whb_r = wh_r[wb_r>0]; Xb_rp = X_rp[wb_r>0,]
Psi_lpq = crossprod(sqrt(whb_l*sigmab_l*wbb_l)*Xb_lp,sqrt(whb_l*sigmab_l*wbb_l)*Xb_lq)
Psi_rpq = crossprod(sqrt(whb_r*sigmab_r*wbb_r)*Xb_rp,sqrt(whb_r*sigmab_r*wbb_r)*Xb_rq)
}
else {
wbh_l = wb_l[wh_l>0]; Xh_lq = X_lq[wh_l>0,]
wbh_r = wb_r[wh_r>0]; Xh_rq = X_rq[wh_r>0,]
Psi_lpq = crossprod(sqrt(whh_l*sigmah_l*wbh_l)*Xh_lp,sqrt(whh_l*sigmah_l*wbh_l)*Xh_lq)
Psi_rpq = crossprod(sqrt(whh_r*sigmah_r*wbh_r)*Xh_rp,sqrt(whh_r*sigmah_r*wbh_r)*Xh_rq)
}
Hp = diag(c(1,poly(h,degree=p,raw=T)))
Cov_l = invGamma_lp%*%Psi_lpq%*%invGamma_lq; Cov_r = invGamma_rp%*%Psi_rpq%*%invGamma_rq
v_lp = t(Xh_lp*whh_l)%*%(uhh_l^(p+1)); v_rp = t(Xh_rp*whh_r)%*%(uhh_r^(p+1))
BiasConst_lp = factorial(deriv)*Hp%*%invGamma_lp%*%v_lp; BiasConst_rp = factorial(deriv)*Hp%*%invGamma_rp%*%v_rp
Bias_tau = (tau_rq[p+2,1]*BiasConst_rp[deriv+1,1] - tau_lq[p+2,1]*BiasConst_lp[deriv+1,1])*(h^(p+1-deriv)/factorial(p+1))
V_l_cl = factorial(deriv)^2*V_lp[deriv+1,deriv+1]
V_r_cl = factorial(deriv)^2*V_rp[deriv+1,deriv+1]
V_l_rb = factorial(deriv)^2*V_lp[deriv+1,deriv+1] + factorial(p+1)^2*V_lq[p+2,p+2]*(BiasConst_lp[deriv+1]*h^(p+1-deriv)/factorial(p+1))^2 - 2*factorial(deriv)*factorial(p+1)*Cov_l[deriv+1,p+2]*(BiasConst_lp[deriv+1]*h^(p+1-deriv)/factorial(p+1))
V_r_rb = factorial(deriv)^2*V_rp[deriv+1,deriv+1] + factorial(p+1)^2*V_rq[p+2,p+2]*(BiasConst_rp[deriv+1]*h^(p+1-deriv)/factorial(p+1))^2 - 2*factorial(deriv)*factorial(p+1)*Cov_r[deriv+1,p+2]*(BiasConst_rp[deriv+1]*h^(p+1-deriv)/factorial(p+1))
V_cl = scalepar^2*(V_l_cl + V_r_cl)
V_rb = scalepar^2*(V_l_rb + V_r_rb)
tau_Y = c(scalepar*(tau_rp[deriv+1,1] - tau_lp[deriv+1,1]), scalepar*(tau_rp[deriv+1,1] - tau_lp[deriv+1,1] - Bias_tau), scalepar*(tau_rp[deriv+1,1] - tau_lp[deriv+1,1] - Bias_tau))
se_Y = c(sqrt(V_cl),sqrt(V_cl),sqrt(V_rb))
t_Y = tau_Y/se_Y
pv_Y = 2*pnorm(-abs(t_Y))
ci_Y = matrix(NA,nrow=3,ncol=2)
rownames(ci_Y)=c("Conventional","Bias-Corrected","Robust")
colnames(ci_Y)=c("Lower","Upper")
ci_Y[1,] = c(tau_Y[1] - quant*se_Y[1], tau_Y[1] + quant*se_Y[1])
ci_Y[2,] = c(tau_Y[2] - quant*se_Y[2], tau_Y[2] + quant*se_Y[2])
ci_Y[3,] = c(tau_Y[3] - quant*se_Y[3], tau_Y[3] + quant*se_Y[3])
if (type == "fuzzy") {
# First Stage
sigmah_T_l = c(rdvce(X=Xh_l, y=Th_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmah_T_r = c(rdvce(X=Xh_r, y=Th_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_T_l = c(rdvce(X=Xb_l, y=Tb_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_T_r = c(rdvce(X=Xb_r, y=Tb_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
out.lp = qrreg(Xh_lp, Th_l, whh_l, sigmah_T_l)
out.rp = qrreg(Xh_rp, Th_r, whh_r, sigmah_T_r)
out.lq = qrreg(Xb_lq, Tb_l, wbb_l, sigmab_T_l)
out.rq = qrreg(Xb_rq, Tb_r, wbb_r, sigmab_T_r)
tau_T_lp = factor_p*out.lp$beta.hat
tau_T_rp = factor_p*out.rp$beta.hat
tau_T_lq = factor_q*out.lq$beta.hat
tau_T_rq = factor_q*out.rq$beta.hat
V_T_lp = out.lp$Sigma.hat; V_T_rp = out.rp$Sigma.hat
V_T_lq = out.lq$Sigma.hat; V_T_rq = out.rq$Sigma.hat
invGamma_T_lp = out.lp$X.M.X_inv; invGamma_T_rp = out.rp$X.M.X_inv
invGamma_T_lq = out.lq$X.M.X_inv; invGamma_T_rq = out.rq$X.M.X_inv
if (b>=h){
Psi_T_lpq = t(Xb_lp*c(whb_l*sigmab_T_l*wbb_l))%*%Xb_lq
Psi_T_rpq = t(Xb_rp*c(whb_r*sigmab_T_r*wbb_r))%*%Xb_rq
}
else {
Psi_T_lpq = t(Xh_lp*c(whh_l*sigmah_T_l*wbh_l))%*%Xh_lq
Psi_T_rpq = t(Xh_rp*c(whh_r*sigmah_T_r*wbh_r))%*%Xh_rq
}
Cov_T_l = invGamma_T_lp%*%Psi_T_lpq%*%invGamma_T_lq
Cov_T_r = invGamma_T_rp%*%Psi_T_rpq%*%invGamma_T_rq
Bias_T_tau = (tau_T_rq[p+2,1]*BiasConst_rp[deriv+1,1] - tau_T_lq[p+2,1]*BiasConst_lp[deriv+1,1])*(h^(p+1-deriv)/factorial(p+1))
V_T_l_cl = factorial(deriv)^2*V_T_lp[deriv+1,deriv+1]
V_T_r_cl = factorial(deriv)^2*V_T_rp[deriv+1,deriv+1]
V_T_cl = V_T_l_cl + V_T_r_cl
V_T_l_rb = V_T_l_cl + factorial(p+1)^2*V_T_lq[p+2,p+2]*(BiasConst_lp[deriv+1]*h^(p+1-deriv)/factorial(p+1))^2 - 2*factorial(deriv)*factorial(p+1)*Cov_T_l[deriv+1,p+2]*(BiasConst_lp[deriv+1]*h^(p+1-deriv)/factorial(p+1))
V_T_r_rb = V_T_r_cl + factorial(p+1)^2*V_T_rq[p+2,p+2]*(BiasConst_rp[deriv+1]*h^(p+1-deriv)/factorial(p+1))^2 - 2*factorial(deriv)*factorial(p+1)*Cov_T_r[deriv+1,p+2]*(BiasConst_rp[deriv+1]*h^(p+1-deriv)/factorial(p+1))
V_T_rb = V_T_l_rb + V_T_r_rb
tau_T = c(tau_T_rp[deriv+1,1] - tau_T_lp[deriv+1,1], tau_T_rp[deriv+1,1] - tau_T_lp[deriv+1,1] - Bias_T_tau,tau_T_rp[deriv+1,1] - tau_T_lp[deriv+1,1] - Bias_T_tau)
se_T = c(sqrt(V_T_cl), sqrt(V_T_rb), sqrt(V_T_rb))
t_T = tau_T/se_T
pv_T = 2*pnorm(-abs(t_T))
ci_T=matrix(NA,nrow=3,ncol=2)
ci_T[1,] = c(tau_T[1] - quant*se_T[1], tau_T[1] + quant*se_T[1])
ci_T[2,] = c(tau_T[2] - quant*se_T[2], tau_T[2] + quant*se_T[2])
ci_T[3,] = c(tau_T[3] - quant*se_T[3], tau_T[3] + quant*se_T[3])
############ Second Stage
Bias_F_tau = (1/tau_T[1])*Bias_tau - (tau_Y[1]/tau_T[1]^2)*Bias_T_tau
tau_F = c(tau_Y[1]/tau_T[1], tau_Y[1]/tau_T[1] - Bias_F_tau, tau_Y[1]/tau_T[1] - Bias_F_tau)
sigmah_TY_l = c(rdvce(X=Xh_l, y=Yh_l, frd=Th_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmah_TY_r = c(rdvce(X=Xh_r, y=Yh_r, frd=Th_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_TY_l = c(rdvce(X=Xb_l, y=Yb_l, frd=Tb_l, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
sigmab_TY_r = c(rdvce(X=Xb_r, y=Yb_r, frd=Tb_r, p=p, h=h, matches=matches, vce=vce, kernel=kernel))
out.lp = qrreg(Xh_lp, Th_l, whh_l, sigmah_TY_l); out.rp = qrreg(Xh_rp, Th_r, whh_r, sigmah_TY_r)
out.lq = qrreg(Xb_lq, Tb_l, wbb_l, sigmab_TY_l); out.rq = qrreg(Xb_rq, Tb_r, wbb_r, sigmab_TY_r)
V_TY_lp = out.lp$Sigma.hat; V_TY_rp = out.rp$Sigma.hat
V_TY_lq = out.lq$Sigma.hat; V_TY_rq = out.rq$Sigma.hat
invGamma_TY_lp = out.lp$X.M.X_inv; invGamma_TY_rp = out.rp$X.M.X_inv
invGamma_TY_lq = out.lq$X.M.X_inv; invGamma_TY_rq = out.rq$X.M.X_inv
if (b>=h){
Psi_TY_lpq = t(Xb_lp*c(whb_l*sigmab_TY_l*wbb_l))%*%Xb_lq
Psi_TY_rpq = t(Xb_rp*c(whb_r*sigmab_TY_r*wbb_r))%*%Xb_rq
}
else {
Psi_TY_lpq = t(Xh_lp*c(whh_l*sigmah_TY_l*wbh_l))%*%Xh_lq
Psi_TY_rpq = t(Xh_rp*c(whh_r*sigmah_TY_r*wbh_r))%*%Xh_rq
}
Cov_TY_l = invGamma_TY_lp%*%Psi_TY_lpq%*%invGamma_TY_lq
Cov_TY_r = invGamma_TY_rp%*%Psi_TY_rpq%*%invGamma_TY_rq
V_TY_cl = factorial(deriv)^2*(V_TY_lp[deriv+1,deriv+1] + V_TY_rp[deriv+1,deriv+1])
V_F_cl = (1/tau_T[1]^2)*V_cl + (tau_Y[1]^2/tau_T[1]^4)*V_T_cl -(2*tau_Y[1]/tau_T[1]^3)*V_TY_cl
C_F_l_pq = factorial(deriv)*factorial(p+1)*((1/tau_T[1]^2)*Cov_l - (2*tau_Y[1]/tau_T[1]^3)*Cov_TY_l + (tau_Y[1]^2/tau_T[1]^4)*Cov_T_l)
C_F_r_pq = factorial(deriv)*factorial(p+1)*((1/tau_T[1]^2)*Cov_r - (2*tau_Y[1]/tau_T[1]^3)*Cov_TY_r + (tau_Y[1]^2/tau_T[1]^4)*Cov_T_r)
V_F_rb_t2 = -2*(C_F_l_pq[deriv+1,p+2]*BiasConst_lp[deriv+1] + C_F_r_pq[deriv+1,p+2]*BiasConst_rp[deriv+1])*h^(p+1-deriv)/factorial(p+1)
C_YY_lq = factorial(p+1)^2*V_lq[p+2,p+2]
C_YY_rq = factorial(p+1)^2*V_rq[p+2,p+2]
C_TT_lq = factorial(p+1)^2*V_T_lq[p+2,p+2]
C_TT_rq = factorial(p+1)^2*V_T_rq[p+2,p+2]
C_TY_lq = factorial(p+1)^2*V_TY_lq[p+2,p+2]
C_TY_rq = factorial(p+1)^2*V_TY_rq[p+2,p+2]
V_F_cl_lq = (1/tau_T[1]^2)*C_YY_lq + (tau_Y[1]^2/tau_T[1]^4)*C_TT_lq -(2*tau_Y[1]/tau_T[1]^3)*C_TY_lq
V_F_cl_rq = (1/tau_T[1]^2)*C_YY_rq + (tau_Y[1]^2/tau_T[1]^4)*C_TT_rq -(2*tau_Y[1]/tau_T[1]^3)*C_TY_rq
V_F_rb_t3 = (V_F_cl_lq*BiasConst_lp[deriv+1]^2 + V_F_cl_rq*BiasConst_rp[deriv+1]^2)*(h^(p+1-deriv)/factorial(p+1))^2
V_F_rb = V_F_cl + V_F_rb_t2 + V_F_rb_t3
se_F = c(sqrt(V_F_cl),sqrt(V_F_cl), sqrt(V_F_rb))
t_F = tau_F/se_F
pv_F = 2*pnorm(-abs(t_F))
ci_F=matrix(NA,nrow=3,ncol=2)
ci_F[1,] = c(tau_F[1] - quant*se_F[1], tau_F[1] + quant*se_F[1])
ci_F[2,] = c(tau_F[2] - quant*se_F[2], tau_F[2] + quant*se_F[2])
ci_F[3,] = c(tau_F[3] - quant*se_F[3], tau_F[3] + quant*se_F[3])
}
#print("Estimation Completed.")
if (type == "sharp") {
coef=matrix(tau_Y,3,1)
se =matrix(se_Y,3,1)
z =matrix(t_Y,3,1)
pv =matrix(pv_Y,3,1)
ci=ci_Y
}
else if (type == "fuzzy") {
coef=matrix(tau_F,3,1)
se =matrix(se_F,3,1)
z =matrix(t_F,3,1)
pv =matrix(pv_F,3,1)
ci=ci_F
}
bws=matrix(c(h,b),1,2)
rownames(coef)=rownames(se)=rownames(se)=rownames(z)=rownames(pv)=c("Conventional","Bias-Corrected","Robust")
colnames(coef)="Coeff"
colnames(se)="Std. Err."
colnames(z)="z"
colnames(pv)="P>|z|"
colnames(bws)=c("h","b")
rownames(ci)=c("Conventional","Bias-Corrected","Robust")
colnames(ci)=c("CI Lower","CI Upper")
tabl1.str=matrix(NA,4,1)
rownames(tabl1.str)=c("Number of Obs", "NN Matches", "BW Type", "Kernel Type")
dimnames(tabl1.str) <-list(c("Number of Obs", "NN Matches", "BW Type", "Kernel Type"), rep("", dim(tabl1.str)[2]))
tabl1.str[1,1]=N
tabl1.str[2,1]=matches
tabl1.str[3,1]=bwselect
tabl1.str[4,1]=kernel_type
tabl2.str=matrix(NA,6,2)
colnames(tabl2.str)=c("Left","Right")
rownames(tabl2.str)=c("Number of Obs","Order Loc Poly (p)","Order Bias (q)","BW Loc Poly (h)","BW Bias (b)","rho (h/b)")
tabl2.str[1,]=formatC(c(Nh_l,Nh_r),digits=0, format="f")
tabl2.str[2,]=formatC(c(p,p),digits=0, format="f")
tabl2.str[3,]=formatC(c(q,q),digits=0, format="f")
tabl2.str[4,]=formatC(c(h,h),digits=4, format="f")
tabl2.str[5,]=formatC(c(b,b),digits=4, format="f")
tabl2.str[6,]=formatC(c(h/b,h/b),digits=4, format="f")
tabl3.str=matrix("",2,6)
colnames(tabl3.str)=c("Coef","Std. Err.","z","P>|z|","CI Lower","CI Upper")
rownames(tabl3.str)=c("Conventional", "Robust")
tabl3.str[1,1] =formatC(coef[1],digits=4, format="f")
tabl3.str[1,2] =formatC(se[1], digits=4, format="f")
tabl3.str[1,3] =formatC(z[1], digits=4, format="f")
tabl3.str[1,4] =formatC(pv[1], digits=4, format="f")
tabl3.str[1,5:6]=formatC(ci[1,], digits=4, format="f")
tabl3.str[2,4] =formatC(pv[3], digits=4, format="f")
tabl3.str[2,5:6]=formatC(ci[3,] ,digits=4, format="f")
if (all==TRUE){
tabl3.str=formatC(cbind(coef,se,z,pv,ci),digits=4, format="f")
colnames(tabl3.str)=c("Coef","Std. Err.","z","P>|z|","CI Lower","CI Upper")
}
out=list(tabl1.str=tabl1.str,tabl2.str=tabl2.str,tabl3.str=tabl3.str,coef=coef,bws=bws,se=se,z=z,pv=pv,ci=ci,p=p,q=q,h=h,b=b,rho=rho,N=N,N_l=Nh_l,N_r=Nh_r)
out$call <- match.call()
class(out) <- "rdrobust"
return(out)
}
#rdrobust <- function(y,x, ...) UseMethod("rdrobust")
#rdrobust.default <- function(y,x, ...){
# est <- rdrobustEst(y,x, ...)
# est$call <- match.call()
# class(est) <- "rdrobust"
# est
#}
print.rdrobust <- function(x,...){
cat("Call:\n")
print(x$call)
cat("\nSummary:\n")
print(x$tabl1.str,quote=F)
cat("\n")
print(x$tabl2.str,quote=F)
cat("\nEstimates:\n")
print(x$tabl3.str,quote=F)
}
summary.rdrobust <- function(object,...) {
TAB <- cbind(Estimate =object$coef,
"Std. Error"=object$se,
"z" =object$z,
"Pr(>|z|)" =object$pv,
"95% CI" =object$ci)
res <- list(call=object$call, coefficients=TAB)
class(res) <- "summary.rdrobust"
res
}
#print.summary.rdrobust <- function(x, ...){
# cat("Call:\n")
# print(x$call)
# cat("\n")
# printCoefmat(x$coef)
# printCoefmat(x$coefficients, P.values=TRUE, has.Pvalue=TRUE)
#}
### Copyright (c) Sebastian Calonico <scalonico@bus.miami.edu>,
### Matias D. Cattaneo <cattaneo@umich.edu>,
### Rocio Titiunik <titiunik@umich.edu>
###
### This file is part of the rdrobust R package.
###
### Rdrobust is free software: you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation, version 2 of the License.
###
### Rdrobust is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU General Public License for more details.
### You should have received a copy of the GNU General Public License
### along with rdrobust. If not, see <http://www.gnu.org/licenses/>.
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment