[R] looping through 3D array
arun
smartpink111 at yahoo.com
Thu Jan 9 22:10:00 CET 2014
Hi,
No problem.
You can use ?lower.tri() or ?upper.tri()
res[lower.tri(res)]
res[lower.tri(res,diag=TRUE)]
#Other way would be to use:
?combn
indx <- combn(dim(results)[1],m=2)
res2 <- sapply(seq_len(ncol(indx)),function(i) {x1 <- indx[,i]; emd2d(results[x1[1],,],results[x1[2],,]) })
identical(res[lower.tri(res)], res2)
#[1] TRUE
A.K.
On Thursday, January 9, 2014 4:03 PM, alex padron <alexpadron1082 at gmail.com> wrote:
Thanks. This works. I just noticed that half of the matrix repeats. For example res[1,2] is the same as res[2,1]. any way to get half of the matrix output (notice the diagonal 0 across the output matrix)?
-Alex
On Thu, Jan 9, 2014 at 12:57 PM, arun <smartpink111 at yahoo.com> wrote:
#or
>you can use ?expand.grid() and then loop over:
>indx <- expand.grid(rep(list(seq(dim(results)[1])),2))
>res1 <- matrix(sapply(seq_len(nrow(indx)),function(i) {x1 <- indx[i,]; emd2d(results[x1[,1],,],results[x1[,2],,]) }),ncol=10)
>identical(res,res1)
>#[1] TRUE
>
>
>
>
>
>On Thursday, January 9, 2014 3:46 PM, arun <smartpink111 at yahoo.com> wrote:
>Hi,
>Try:
>library(emdist)
>
>set.seed(435)
>results<- array(sample(1:400,120,replace=TRUE),dim=c(10,3,4))
>res <- sapply(seq(dim(results)[1]),function(i) {x1 <- results[i,,]; x2 <- results; sapply(seq(dim(x2)[1]),function(i) emd2d(x1,x2[i,,]))})
>dim(res)
>#[1] 10 10
>A.K.
>
>
>
>
>
>
>
>On Thursday, January 9, 2014 3:25 PM, alex padron <alexpadron1082 at gmail.com> wrote:
>
>I'll try to be clearer. in your example we have: results<- array(1:120,dim=c(10,3,4))
>
>I want to do the following: compare results[1,,] with every matrix inside results. I then want to jump to results[2,,] and compare it to all of the other 10 matrices inside results and so on. so emd2d from the emdist package outputs a single value when comparing matrices and since your example has 10 matrices who are all being compared, the output should be 100 values.
>
>Does that make sense?
>
>
>-Alex
>
More information about the R-help
mailing list