Skip to content

Alternating between "for loops"

1 message · Rui Barradas

#
Hello,

You're right, and there's a way without loops. Summarizing:


J <- 10
N <- 10

cols <- rep(c(TRUE, TRUE, FALSE, FALSE), ceiling(J / 4))[seq_len(J)]

#--- 1st way: nested loops
y <- matrix(0, N, J)
for(j in which(cols)){
     for (q in 1:N)
         y[q, j] <- if(j %% 2) 1 else 2
}
for(j in which(!cols)){
     for (q in 1:N)
         y[q, j] <- if(j %% 2) "A" else "B"
}

#--- 2nd way: one loop only
z <- matrix(0, N, J)
for(j in which(cols))
     z[, j] <- if(j %% 2) 1 else 2
for(j in which(!cols))
     z[, j] <- if(j %% 2) "A" else "B"

#--- 3rd way: no loops
w <- matrix(0, J, N)  # reversed order
w[cols, ] <- ifelse(which(cols) %% 2, 1, 2)
w[!cols, ] <- ifelse(which(!cols) %% 2, "A", "B")
w <- t(w)

identical(y, z) # compare original to each
identical(y, w) # of the other results

Em 31-07-2012 23:54, Mercier Eloi escreveu: