-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy path24.2_BehavioralLearningExperiment.R
90 lines (76 loc) · 2.33 KB
/
24.2_BehavioralLearningExperiment.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
## Read the data & redefine variables
# Data are at http://www.stat.columbia.edu/~gelman/arm/examples/dogs
library(rstan)
library(ggplot2)
library(reshape2)
y1 <- as.matrix (read.table ("dogs.dat"), nrows=30, ncol=25)
y <- ifelse (y1[,]=="S",1,0)
n.dogs <- nrow(y)
n.trials <- ncol(y)
## Calling predictive replications in Bugs
dataList.1 <- list(n_dogs=n.dogs,n_trials=n.trials,y=y)
dogs.sf1 <- stan(file='dogs.stan', data=dataList.1, iter=1000, chains=4)
print(dogs.sf1, pars = c("beta","lp__"))
post <- extract(dogs.sf1)
beta <- colMeans(post$beta)
## Pedictive replications in R
n.sims <- 4000
y.rep <- array (NA, c(n.sims, n.dogs, n.trials))
for (j in 1:n.dogs){
n.avoid.rep <- rep (0, n.sims)
n.shock.rep <- rep (0, n.sims)
for (t in 1:n.trials){
p.rep <- invlogit (beta[1] + beta[2]*n.avoid.rep + beta[3]*n.schok.rep)
y.rep[,j,t] <- rbinom (n.sims, 1, p.rep)
n.avoid.rep <- n.avoid.rep + 1 - y.rep[,j,t]
n.shock.rep <- n.shock.rep + y.rep[,j,t]
}
}
## Direct comparison of simulated to real data
dogsort <- function (y){
n.dogs <- nrow(y)
n.trials <- ncol(y)
last.shock <- rep (NA, n.dogs)
for (j in 1:n.dogs){
last.shock[j] <- max ((1:n.trials)[y[j,]==1])
}
y[order(last.shock),]
}
## More focused model checks
# Figure 24.2a
test <- function (data){
colMeans (1-data)
}
y.sim <- melt(y.rep)
frame = data.frame(x1=0:(n.trials-1),y1=test(y.sim[,,],newpid=newpid))
p1 <- ggplot(frame,aes(x=x1,y=y1)) +
geom_point() +
scale_y_continuous("sqrt (CD4%)") +
scale_x_continuous("Time (years)") +
theme_bw() +
labs(title="Observed Data")
for (j in 1:84) {
p1 <- p1 + geom_line(data=frame[frame$newpid==unique.pid[j],])
}
print(p1)
# Figure 24.2b
test.diff <- function (data, data.rep){
test (data) - test (data.rep)
}
diff.range <- NULL
for (s in 1:20){
diff.range <- range (diff.range, test.diff (y, y.rep[s,,]))
}
dev.new()
y.sim <- melt(y.rep)
frame = data.frame(x1=0:(n.trials-1),y1=test.diff(y,y.sim[,,]),newpid=newpid)
p2 <- ggplot(frame,aes(x=x1,y=y1)) +
geom_point() +
scale_y_continuous("sqrt (CD4%)") +
scale_x_continuous("Time (years)") +
theme_bw() +
labs(title="Observed Data")
for (j in 1:84) {
p2 <- p2 + geom_line(data=frame[frame$newpid==unique.pid[j],])
}
print(p2)