[R] R code help!

SH emptican at gmail.com
Mon Sep 21 17:06:54 CEST 2015


Hi Jean,

Thank you so much!

Steve

On Sat, Sep 19, 2015 at 1:02 PM, Adams, Jean <jvadams at usgs.gov> wrote:

> Here's one way to save your results, using a list of lists and a for()
> loop.
>
> nsim <- 100
> outputs <- vector("list", nsim)
> for(i in 1:nsim) {
>   outputs[[i]] <- sim.f(p.s=.05, N=1000, sample.size=69, n.sim=500)
> }
>
> Jean
>
> On Fri, Sep 18, 2015 at 2:27 PM, SH <emptican at gmail.com> wrote:
>
>> 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]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list