# [R] How to combine two loops?

Jim Lemon jim at bitwrit.com.au
Sun Jan 13 07:40:29 CET 2013

```On 01/13/2013 05:15 PM, Agnes Ayang wrote:
> Hello R-helpers,
>
> I want to ask your opinion since I am not so sure how to do it. This is regarding one part of my paper project and my situation is:
>
> Stage I
>
> I have 2 groups and for each group I need to compute the following steps;
>
> i) Generate 3 random numbers from normal distribution and square them.
> ii) Repeat step 1 for 15 times and at the end I will get 15 random numbers.
>
> I already done stage I using for loop.
>
> n1<-3
> n2<-3
> miu<-0
> sd1<-1
> sd2<-1
> asim<-15
> w<-rep(NA,asim)
> x<-rep(NA,asim)
> for (i in 1:asim)
> {
> print(i)
> set.seed(i)
> data1<-rnorm(n1,miu,sd1)
> data2<-rnorm(n2,miu,sd2)
> w[i]<-sum(data1^2)
> x[i]<-sum(data2^2)
> }
> w
> x
>
> Second stage is;
>
> Stage II
>
> For each group, I need to:
> i) Sort the group;
> ii) Find trimmed mean for each group.
>
>
> For the whole process (stage I and stage II) I need to simulate them for 5000 times. How am I going to proceed with step 2? Do you  think I need to put another loop to proceed with stage II?
>
> Thank you and I appreciate the time you spent to look at my problem.
>
Hi Agnes,
We don't do people's homework for them, but you should probably look at:

the "sort" function
the "mean" function
the "list" function (for holding large numbers of things like vectors)
the "lapply" function (for applying a function to the members of a list)
the "set.seed" function - setting the seed to the same number(s) will
produce the same sequence of random numbers. Is this what you want?
You are generating two sets of random numbers with each cycle of the
loop, and collecting "sums of squares" for both. Do you know why?

Good luck

Jim

```