clarified description
[s290-pingpong] / ping_pong_ball_jar_simulation.R
1 ## simluation 
2 ############################################################
3
4 pingpong <- get.ping.pong.ball
5 reset.weights()
6
7 # create a non-weighted function to compare
8 pingpong.nonweighted <- function () {
9   return(sample(member.names, 1))
10 }
11
12 # function to run a simulation and generate 1000 classes
13 run.simulation <- function (pingpong.fun, questions=10) {
14
15   d <- c()
16   # run the comand 1000 times
17   for (i in seq(1,1000)) {
18
19     all.prev <- c()
20     reset.weights()
21     for (j in seq(1,questions)) {
22       selected <-  pingpong.fun()
23       all.prev <- append(all.prev, selected)
24     }
25
26     d <- append(d, table(all.prev))
27
28     missing.names <- names(w)[sapply(names(w),
29                                      function (x) {!x %in% names(table(all.prev))})]
30     d.tmp <- rep(0, length(missing.names))
31     names(d.tmp) <- missing.names
32
33     d <- append(d, d.tmp)
34   }
35
36   total.nums <- sapply(names(w),
37                        function (x) {sum(d[names(d) == x])})
38
39   cat("Number of total selections:\n")
40   print(total.nums)
41   cat(paste("SD:", sd(total.nums), "\n"))
42
43   return(d)
44 }
45
46 d.nw <- run.simulation(pingpong.nonweighted, 15)
47 d.w <- run.simulation(pingpong, 15)
48
49 library(ggplot2)
50
51 graph.sim.output <- function (d, label.text="") {
52   qplot(as.factor(names(table(d))), as.integer(table(d)), geom="bar") +
53     scale_x_discrete("Number of questions asked to participant") +
54     scale_y_continuous("Number of occurances") +
55     opts(title = paste(label.text, "- 1000 classes of 15 questions"))
56 }
57
58 p.weighted <- graph.sim.output(d.w, "weighted")
59 p.nonweighted <- graph.sim.output(d.nw, "non-weighted")
60
61 png("simulation_weighted.png")
62 print(p.weighted)
63 dev.off()
64
65 png("simulation_unweighted_random.png")
66 p.nonweighted
67 dev.off()

Benjamin Mako Hill || Want to submit a patch?