[R] How to avoid for or while loops when one index depends on another
Gabor Grothendieck
ggrothendieck at gmail.com
Fri Mar 24 14:13:55 CET 2006
Here are a few alternatives to try. I doubt they are particularly
efficient but if you want to compare them see ?system.time
n <- 4
dd <- expand.grid(i = 1:n, j = 1:n)[upper.tri(diag(n), diag = FALSE),]
for(r in 1:nrow(dd)) with(dd[r,], cat(i, j, "\n"))
library(gtools)
dd <- structure(as.data.frame(combinations(n,2)), .Names = c("i", "j"))
for(r in 1:nrow(dd)) with(dd[r,], cat(i, j, "\n"))
mat <- matrix(seq(n*n), n)
for(idx in seq(mat)[upper.tri(mat)]) {
i <- row(mat)[idx]
j <- col(mat)[idx]
cat( i, j, "\n")
}
for(i in seq(n)) for(j in seq(n)[-seq(i)]) cat(i, j, "\n")
On 3/24/06, Daniel Goldstein <dgoldstein at london.edu> wrote:
> Dear R Community,
>
> I'm trying to exploit the elegance of R by doing the following
> pseudocode routine without a WHILE or FOR loop in R:
>
> for i = 1 to length-1
> for j = (i+1) to length
> print a[i], a[j]
>
> That is, I want i and j to be the indices of a half-matrix
> 1 2, 1 3, 1 4, ..., 1 length,
> 2 3, 2 4, ..., 2 length,
> 3 4, ..., 3 length
>
> 1. Can this be done with the 'whole object' approach (Introduction to R
> v2.1.1 section 9.2.2) and not while loops?
>
> 2. (Extra credit) Is your solution likely to be more efficient than a loop?
>
> 3. (Extra credit) How could once do this with FOR as opposed to WHILE in
> R? Clearly if you attempt "j in i+1:length" you're in trouble when i
> exceeds length.
>
> Thanks for your help with this excellent open-source resource,
> Dan
>
> --
> Daniel Goldstein, Ph.D.
> Assistant Professor of Marketing
> London Business School s234
> Regent's Park, Sussex Place
> London NW1 4SA, United Kingdom
> p: +44 (0) 20 7706 6796
> f: +44 (0) 20 7724 1145
> www.dangoldstein.com
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list