[R] What am I doing wrong in my loops?

James Rome jamesrome at gmail.com
Wed Dec 30 17:52:56 CET 2009


Dear kind list people:

I have the following code:
>hours
 [1] "0"  "1"  "2"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13"
"14" "15"
[16] "16" "17" "18" "19" "20" "21" "22" "23"
> alist
$`0`
 [1]  3 10 10  6  5  6  4  8  9  3  7  5  8  3  6  7  2  6  6  1  4  8
10  4 10
[26] 13  6  2  8  4  7  3  4  7  9  6  4  7  4  4  4  3

$`1`
[1] 1 1 3 2 3 4 2 1

$`2`
[1] 1 1 3 3
. . .
mn=c(length(alist)*1000)
il=c(length(alist)*1000)
# Now calculate the means
for(i in 1:length(alist)) {
 for(j in 1:1000) {mn[i*j]=mean(sample(alist[[i]], 1000, replace=TRUE));
il[i*j]= hours[i]}}

But not even the il vector is correct:
>il
    [1] "0"  "1"  "2"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13"
"14"
   [15] "15" "16" "17" "18" "19" "20" "21" "22" "23" "12" "5"  "13" "9" 
"14"
   [29] "0"  "15" "0"  "16" "11" "17" "7"  "18" "0"  "19" "13" "20" "0" 
"21"
   [43] "0"  "22" "15" "23" "0"  "16" "7"  "10" "17" "13" "0"  "18" "11"
"14"
   [57] "19" "1"  "0"  "20" "0"  "1"  "21" "16" "13" "22" "0"  "17" "23"
"14"
   [71] "0"  "18" "0"  "1"  "15" "19" "11" "13" "0"  "20" "9"  "1"  "0" 
"21"
 . . .
and after a while, both mn and il get lots of NAs. The first 1000
entries should be "0".

What am I doing wrong?

And is there a way to do this without the two for loops?

Thanks,
Jim Rome




More information about the R-help mailing list