[R] R: LIST function and LOOPS
Clark Allan
Allan at STATS.uct.ac.za
Thu Mar 10 09:16:55 CET 2005
hi all
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
[1] -0.01516304
what i want is something that looks like this:
j=1
$ss
[1] -2.213343
j=2
$ss
[1] -2.904235
j=3
$ss
[1] -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)
[1] -2.213343
[1] -2.904235
[1] -0.01516304
> check.2
[1] -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
$b
1
2
3
4
5
$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
More information about the R-help
mailing list