[R] R code help!
SH
emptican at gmail.com
Fri Sep 18 21:27:08 CEST 2015
Dear R users,
I am trying to simulate surveys and the survey result will be used to
determine the population to be "accepted" or "rejected". With the results,
I would like to calculate cumulative means and plot them to see if a
converged value is as expected. Below is R-code I generated. I need a
help to repeat this simulation code as many times (e.g., 100) and keep the
results as list format if possible. Could you give me any insight?
Thanks a lot in advance,
Steve
sim.f <- function(p.s, N, sample.size, n.sim) {
pop = sampled.pop = decision = decisionB = cum.mn = as.list(NULL)
for(i in 1:n.sim) {
p <- c(rep(1, p.s*N), pop2 <- rep(0, N*(1-p.s))) # Generate sample space
pop[[i]] <- sample(p) # Randomization sample space
sampled.pop[[i]] <- sample(pop[[i]], sample.size)# Random sampling
decision[i] <- ifelse(sum(sampled.pop[[i]])>=1, 'Reject','Pass') #
Decision for each group of n.sim
decisionB <- ifelse(decision == 'Reject', 1, 0) # Convert to binary
cum.mn <- cumsum(decisionB) / seq_along(decisionB) # Cummulative mean of
n.sim group decisions
}
result = list(population=pop,
pop_sub = sampled.pop,
decision = decision,
decisionB = decisionB,
cum.mn = cum.mn)
}
sim.out <- sim.f(p.s=.05, N=1000, sample.size=69, n.sim=500)
# I want to repeat this simulation function for example 100 times or and
also #keep the data so that I can explore later. If it is not possible to
keep all #outputs, at least I would like to have cum.mn outputs.
summary(sim.out)
sim.out$population
sim.out$pop_sub
sim.out$decision
sim.out$decisionB
y1 <- sim.out$cum.mn
#plot(y1, type='l')
lines(y2, type='l')
...
lines(y100, type='l')
abline(h=.95, col='red')
[[alternative HTML version deleted]]
More information about the R-help
mailing list