[R] Nested Loop in R

Ko-Kang Kevin Wang k.wang at auckland.ac.nz
Tue Apr 6 00:19:28 CEST 2004


Hi,

Apologies for such a trivial question, but it has been over two years since
I last used nested loops and I'm ashamed to say that I forgot how they work
*_*....

Suppose I've the following codes:
#####
x <- round(runif(1000, 1, 6))
samp5 <- vector(mode = "list", length = 5)

for(i in 1:5) {
  samp5[[i]] <- sample(x, 5)
}

plot.new()
plot.window(xlim = c(1, 6), ylim = c(1, 5))
axis(1, at = 1:6)
axis(2, at = 1:5, labels = 5:1, las = 1)
points(jitter(samp5[[1]], 0.1), rep(5, 5))
lines(x = c(mean(samp5[[1]]), mean(samp5[[1]])),
      y = c(5.1, 4.9))
points(jitter(samp5[[2]], 0.1), rep(4, 5))
lines(x = c(mean(samp5[[2]]), mean(samp5[[2]])),
      y = c(4.1, 3.9))
points(jitter(samp5[[3]], 0.1), rep(3, 5))
lines(x = c(mean(samp5[[3]]), mean(samp5[[3]])),
      y = c(3.1, 2.9))
points(jitter(samp5[[4]], 0.1), rep(2, 5))
lines(x = c(mean(samp5[[4]]), mean(samp5[[4]])),
      y = c(2.1, 1.9))
points(jitter(samp5[[5]], 0.1), rep(1, 5))
lines(x = c(mean(samp5[[5]]), mean(samp5[[5]])),
      y = c(1.1, 0.9))
#####

and wanted to convert them into a function like:
#####
clt <- function(x, samp.no = 5, n = 5) {
  samp <- vector(mode = "list", length = samp.no)
  plot.new()
  plot.window(xlim = c(1, 6), ylim = c(1, samp.no))
  axis(1, at = 1:6)
  axis(2, at = 1:samp.no, labels = samp.no:1, las = 1)

  for(i in 1:samp.no) {
    samp[[i]] <- sample(x, n)
    for(j in n:1) {
      points(jitter(samp[[i]], 0.1), rep(j, n))
      lines(x = c(mean(samp[[i]]), mean(samp[[i]])),
            y = c(j - 0.1, j + 0.1))
    }
  }
}

clt(x)
#####

But it didn't quite work and I can see the problem occurs within the nested
loop.  Can anyone spot my mistake?

Thank you very much in advance!

Kevin




More information about the R-help mailing list