-
Notifications
You must be signed in to change notification settings - Fork 0
/
pres_12.R
91 lines (66 loc) · 1.79 KB
/
pres_12.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
## Packages
library(rdd)
library(rdpower)
library(rdrobust)
library(tidyverse)
library(tidymodels)
library(readr)
library(sf)
## Data
data <- read_sf("Datasets/election/election.shp")
## Basic Plot
data %>%
ggplot(aes(x = RHI125214, y = pct_dem_12)) +
geom_point() +
theme_bw()
## Setting Seed
set.seed(123889)
## Saving Percentiles (Candidate Cut-points)
g <- percentile(data$RHI125214)
## Initializing Data Frame
f <- data.frame(1)
## Creates the Candidate (x-c)'s
for (i in 1:length(g)) {
p <- paste0("X_", i)
c <- assign(p, (data$RHI125214 - g[i]))
f <- data.frame(c, f)
}
## Drop the needed initialized column
f <- f %>%
select(-X1)
## Testing Equivalencies
q <- data$RHI125214-g[45]
q == f$c.45
## Initializing Variables for local linear regression loop
models <- list()
f <- f %>%
select(-c) %>%
cbind(data$pct_dem_12)
variables <- setdiff(names(f), c("row_id"))
## Local Linear Regression Loop
for (var in variables) {
skip_to_next <- FALSE
tryCatch(models[[var]] <- RDestimate(
as.formula(paste0("data$RHI125214 ~ ", var)),
data = f
), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
## Testing
selection_criteria("c.49")
summary(RDestimate(`data$pct_dem_12`~ c.3, data=f))
x <- RDestimate(`data$pct_dem_12`~ c.3, data=f)
plot(x)
## Creating Cuts Name
cuts <- colnames(f)
## Finding Optimal Cut-point
s <- sapply(cuts, selection_criteria, USE.NAMES = TRUE)
s[s== max(s)]
df <- data.frame(s)
library(rdrobust)
rdplot(data$pct_dem_12, data$RHI125214, c=58, kernel = "triangular", binselect = "es",
title = "Tipping-point for Minority Voters Electing Minority Candidate")
ggplot(df, aes(x=s)) +
geom_histogram() +
theme_minimal() +
labs(title="Distribution of Selection Criteria", x = "Selection Criteria", ylab=NULL)