]> code.communitydata.science - ml_measurement_error_public.git/blob - irr/simex_sim.R
Add simulation using simex
[ml_measurement_error_public.git] / irr / simex_sim.R
1 ##install.packages(c("purrr", "simex", "irr"))
2
3 .emulate_coding <- function(ground_truth, Q = 1) {
4     if (runif(1) > Q) {
5         return(sample(c(0, 1), size = 1, replace = TRUE))
6     } else {
7         return(ground_truth)
8     }
9 }
10
11 distort_gt <- function(x, Q = NULL) {
12     return(purrr::map_dbl(x, .emulate_coding, Q = Q))
13 }
14
15 N <- c(1000, 3600, 14400)
16 m <- c(75, 150, 300)
17
18 B0 <- c(0, 0.1, 0.3)
19 Bxy <- c(0.1, 0.2, 0.5)
20
21 Q <- c(.6, .8, .9)
22
23 conditions <- expand.grid(N, m, B0, Bxy, Q)
24
25 logistic <- function(x) {1/(1+exp(-1*x))}
26
27 .step <- function(Bxy, B0, Q, N, m) {
28     x <- rbinom(N, 1, 0.5)
29     y <-  Bxy * x + rnorm(N, 0, .5) + B0
30
31     dx <- as.numeric(distort_gt(x, Q = Q))
32
33     randomx <- sample(x, m)
34     coder1x <- distort_gt(randomx, Q = Q)
35     coder2x <- distort_gt(randomx, Q = Q)
36     coding_data <- matrix(c(as.numeric(coder1x), as.numeric(coder2x)), nrow = 2, byrow = TRUE)
37     alpha <- irr::kripp.alpha(coding_data, method = "nominal")
38     estimated_q <- alpha$value^(1/2)
39     estimated_q2 <- alpha$value
40
41     res <- data.frame(x = as.factor(x), y = y, dx = as.factor(dx))
42
43     naive_mod <- glm(y~dx, data = res, x = TRUE, y = TRUE)
44     real_mod <- glm(y~x, data = res, x = TRUE, y = TRUE)
45
46     px <- matrix(c(estimated_q, 1-estimated_q, 1-estimated_q, estimated_q), nrow = 2)
47     colnames(px) <- levels(res$dx)
48     corrected_mod <- simex::mcsimex(naive_mod, SIMEXvariable = "dx", mc.matrix = px, jackknife.estimation = FALSE, B = 300)
49     px2 <- matrix(c(estimated_q2, 1-estimated_q2, 1-estimated_q2, estimated_q2), nrow = 2)
50     colnames(px2) <- levels(res$dx)
51     corrected_mod2 <- simex::mcsimex(naive_mod, SIMEXvariable = "dx", mc.matrix = px2, jackknife.estimation = FALSE, B = 300)
52
53     return(tibble::tibble(N, m, Q, Bxy, B0, estimated_q, naive_Bxy = as.numeric(coef(naive_mod)[2]), real_Bxy = as.numeric(coef(real_mod)[2]), corrected_Bxy = coef(corrected_mod)[2], corrected_Bxy2 = coef(corrected_mod2)[2]))
54 }
55
56 ## res <- .step(0.2, 0, 0.8, N = 1000, m = 100)

Community Data Science Collective || Want to submit a patch?