Re: [R] Double for loop

From: sigalit mangut-leiba <smangut_at_gmail.com>
Date: Thu, 26 Jun 2008 12:37:21 +0300

Thank you for your help

On 6/26/08, jim holtman <jholtman_at_gmail.com> wrote:
>
> You can at least get rid of the
>
> for (i in 1:200){
> y[i]<-rbinom(1,1,0.8)
> x1[i]<-ifelse(y[i]==1,rnorm(1,mean=20, sd=2),rnorm(1,mean=16, sd=2.2))
> ....
>
> loop with the following
>
> y <- rbinom(200, 1, 0.8)
> y.1 <- y == 1 # get logical vector of y == 1
> x1 <- numeric(200) # allocate the vector
> x1[y.1] <- rnorm(sum(y.1), 20, 2)
> x1[!y.1] <- rnorm(sum(!y.1), 16, 2.2)
>
> I don't know what else you are doing in the loops, but you should be
> thinking "vectorized" when using R and avoid 'for' loops since they
> are not the most efficient way of going things, especially if you are
> going to be them hunreds of times.
>
> On Thu, Jun 26, 2008 at 4:23 AM, sigalit mangut-leiba <smangut_at_gmail.com>
> wrote:
> > Hi,
> > I'm trying to do a double for loop like this:
> > for (k in 1:1000){
> > for (i in 1:200){
> > y[i]<-rbinom(1,1,0.8)
> > x1[i]<-ifelse(y[i]==1,rnorm(1,mean=20, sd=2),rnorm(1,mean=16, sd=2.2))
> > ....
> > }
> > for (j in 1:300){
> > ....
> > }
> > }
> > Does anyone know a good reference about double loops?
> > Thank you,
> > Sigalit
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help_at_r-project.org 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.
> >
>
>
>
> --
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
>
> What is the problem you are trying to solve?
>

        [[alternative HTML version deleted]]



R-help_at_r-project.org 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. Received on Thu 26 Jun 2008 - 09:41:17 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 26 Jun 2008 - 11:31:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive