1 Aug 2012 01:54
Re: Alternating between "for loops"
Rui Barradas <ruipbarradas <at> sapo.pt>
2012-07-31 23:54:36 GMT
2012-07-31 23:54:36 GMT
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)
(Continue reading)
RSS Feed