-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.R
72 lines (53 loc) · 1.47 KB
/
helpers.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
matrix2df <- function(m, origin = c("bottom-left", "top-left")){
origin <- match.arg(origin)
nr <- nrow(m)
nc <- ncol(m)
n <- nr*nc
out <- data.frame(x = rep(seq_len(nr), nc),
y = rep(seq_len(nc), each = nr),
s = NA)
for(i in 1:n){
x_ind <- out$x[i]
y_ind <- switch (origin,
"bottom-left" = out$y[i],
"top-left" = nc + 1 - out$y[i]
)
out$s[i] <- m[x_ind, y_ind]
}
return(out)
}
rwald <- function(n=1, alpha, nu){
mu <- alpha/nu
lambda <- alpha^2
zeta <- rnorm(n)
zeta_sq <- zeta^2
x <- mu + (mu^2*zeta_sq)/(2*lambda) - mu/(2*lambda)*sqrt(4*mu*lambda*zeta_sq + mu^2*zeta_sq^2)
z <- runif(n)
which_x <- z <= mu / (mu+x)
out <- rep(NA, n)
out[ which_x] <- x[which_x]
out[!which_x] <- mu^2/x[!which_x]
return(out)
}
rtnorm <- function(n=1, mean=0, sd=1, lb = 0, ub = Inf){
pl <- pnorm(lb, mean, sd)
pu <- pnorm(ub, mean, sd)
pp <- runif(n, pl, pu)
qnorm(pp, mean, sd)
}
my_sapply <- function(X, FUN, ...){
ll <- lapply(X, FUN, ...)
ll <- do.call(rbind, ll)
ll <- as.data.frame(ll)
return(ll)
}
fits2rank <- function(fits, sim_par, name_par){
if(length(fits) != length(sim_par)) stop("fits and sim_par need the same length")
ranks <- sapply(seq_along(fits), function(i){
par_prior <- sim_par[i]
par_post <- rstan::extract(fits[[i]])[[name_par]]
rank <- sum(par_prior <= par_post)
rank
})
return(ranks)
}