# [R] R: LIST function and LOOPS

From: Clark Allan <Allan_at_STATS.uct.ac.za>
Date: Thu 10 Mar 2005 - 19:16:55 EST

another simple question.

i've written a dummy program so that you get the concept. (the code could be simplfied such that there are no loops. but lets leave the loops in for now.)

z1<-function(w)
{
for (i in 1:w)
{
set.seed(i+6)
ss<-0

```	for (j in 1:5)
{
set.seed(j+1+(i-1)*6)
r<-rnorm(1)
ss<-ss+r
}
```

list(ss=ss)
}
}
check.1<-z1(3)
check.1

the results is:
\$ss

 -0.01516304

what i want is something that looks like this:

j=1
\$ss

 -2.213343

j=2
\$ss

 -2.904235

j=3
\$ss

 -0.01516304

i know that i could use the print command. (see z2)

z2<-function(w)
{
for (i in 1:w)
{
set.seed(i+6)
ss<-0

```	for (j in 1:5)
{
set.seed(j+1+(i-1)*6)
r<-rnorm(1)
ss<-ss+r
}
```

print(ss)
}
}
check.2<-z2(3)
check.2

> check.2<-z2(3)

``` -2.213343
 -2.904235
 -0.01516304
```

> check.2
 -0.01516304

the problem with z2 is that only the last value is saved.

what i could do is use matrices like the following: (but i dont want to do this AND WOULD PREFER TO USE list.)

z3<-function(w)
{
results.<-matrix(nrow=w,ncol=1)
colnames(results.)<-c("ss")
for (i in 1:w)
{
set.seed(i+6)
ss<-0

```	for (j in 1:5)
{
set.seed(j+1+(i-1)*6)
r<-rnorm(1)
ss<-ss+r
}
```

results.[i,1]<-ss
}
results.
}
check.3<-z3(3)
check.3

> check.3

ss

```[1,] -2.21334260
[2,] -2.90423463
[3,] -0.01516304

```

what if i have a new program (something different) and i want the following:

j=1
\$a

1
2
3

\$c

1

###############
j=2
\$a

11
21
31

\$b

11
21
31
41
51

\$c

11

###############
j=3
\$a

21
22
32

\$b

21
22
32
42
52

\$c

21

MATRICES SEEMS TO BE A GOOD WAY OF DOING THIS (but then you would have to set up three matrices, one for a,b and c). BUT WHAT IF I WANT TO USE THE LIST FUNCTION? i.e. there is a list in the first loop that i want to display!

sorry for the long mail.

***
ALLAN

R-help@stat.math.ethz.ch mailing list