[R] indexing problem
diana
diana.chirac at free.fr
Tue Oct 19 22:19:11 CEST 2004
Tony, Sundar,
Thank you for your codes, they all work, but the "tricky" code of
Tony seems more efficient than the sapply() solution of Sundar,
especially for big size array. For a quick test:
> dm = matrix(rnorm(100000*40),ncol=40)
> idx=cbind(sample(1:ncol(dm), nrow(dm), replace=T),
sample(1:ncol(dm), nrow(dm),replace=T),
sample(1:ncol(dm), nrow(dm),replace=T))
> str(idx)
int [1:100000, 1:3] 6 2 1 6 24 23 21 36 31 21 ...
> system.time(a <- array(dm[cbind(as.vector(row(idx)), as.vector(idx))], dim=dim(idx)))
[1] 0.12 0.01 0.14 NA NA
> system.time(b <- t(sapply(seq(nrow(dm)), function(i) dm[i, idx[i, ]])))
[1] 1.60 0.00 1.69 NA NA
> all(a==b)
[1] TRUE
diana
More information about the R-help
mailing list