[R] looping
Greg Snow
Greg.Snow at intermountainmail.org
Tue Feb 27 21:47:17 CET 2007
For the example that you give, using lapply, sapply, or replicate may be
the better way to go:
> mysample <- replicate( 50, dataset[ sample(100000,100), ] )
If you really want to use a loop, then use a list:
> mysamples <- list()
> mysampdata <- list()
> for (i in 1:50){
+ mysamples[[i]] <- sample(100000, 100)
+ mysampdata[[i]] <- dataset[ mysamples[[i]], ]
+ }
Then you can use lapply or sapply to do something with each sampled
dataset:
> sapply( mysampdata, summary )
Or you can access individual elements in a number of ways:
> summary( mysampdata[[1]] )
> names(mysampdata) <- paste('d',1:50, sep='')
> with(mysampdata, summary(d2))
> summary( mysampdata$d3 )
> attach(mysampdata)
> summary(d4)
> detach()
Hope this helps,
--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Neil Hepburn
> Sent: Monday, February 26, 2007 5:11 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] looping
>
>
> Greetings:
>
> I am looking for some help (probably really basic) with
> looping. What I want to do is repeatedly sample observations
> (about 100 per sample) from a large dataset (100,000
> observations). I would like the samples labelled sample.1,
> sample.2, and so on (or some other suitably simple naming
> scheme). To do this manually I would
>
> >smp.1 <- sample(100000, 100)
> >sample.1 <- dataset[smp.1,]
> >smp.2 <- sample(100000, 100)
> >sample.2 <- dataset[smp.2,]
> .
> .
> .
> >smp.50 <- sample(100000, 100)
> >sample.50 <- dataset[smp.50,]
>
> and so on.
>
> I tried the following loop code to generate 100 samples:
>
> >for (i in 1:50){
> >+ smp.[i] <- sample(100000, 100)
> >+ sample.[i] <- dataset[smp.[i],]}
>
> Unfortunately, that does not work -- specifying the looping
> variable i in the way that I have does not work since R uses
> that to reference places in a vector (x[i] would be the ith
> element in the vector x)
>
> Is it possible to assign the value of the looping variable in
> a name within the loop structure?
>
> Cheers,
> Neil Hepburn
>
> ===========================================
> Neil Hepburn, Economics Instructor
> Social Sciences Department,
> The University of Alberta Augustana Campus
> 4901 - 46 Avenue
> Camrose, Alberta
> T4V 2R3
>
> Phone (780) 697-1588
> email nhepburn at augustana.ca
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> 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.
>
More information about the R-help
mailing list