Skip to content

Generalising to n-dimensions

7 messages · robin hankin, Laura Bonnett

#
First bit:

 > x <- c(3,2,2)
 > expand.grid(sapply(x,seq_len))
   Var1 Var2 Var3
1     1    1    1
2     2    1    1
3     3    1    1
4     1    2    1
5     2    2    1
6     3    2    1
7     1    1    2
8     2    1    2
9     3    1    2
10    1    2    2
11    2    2    2
12    3    2    2
 >


second bit I'm not sure about.  I didn't quite get why d=2 implied the 
order is 2,1.
Could you post a small self-contained example?

HTH

rksh
Laura Bonnett wrote:

  
    
#
Laura Bonnett wrote:
OK  I think I understand.  The magic package uses this type of 
construction extensively, but not this particular one.

It's trickier than I'd have expected.

Try this:

f <- function(a,v){
    jj <- 
sapply(dim(a)[seq_len(length(dim(a))-length(v))],seq_len,simplify=FALSE)
    jj <- c(jj , as.list(v))
    do.call("[" , c(list(a) , jj, drop=TRUE))
}



[you will have to coerce the output from expand.grid() to a matrix in 
order to extract a row from it]


HTH

rksh
1 day later
1 day later
#
Laura Bonnett wrote:
Hi Laura.  I've been away (in Norwich).  Sorry not to give an example.

Variable 'a' is an array and variable 'd' is the same as in your 
original email.


 > a <- array(1:4,c(3,2,2,4))
 > d <- c(1,2)
 > f(a,d)
     [,1] [,2]
[1,]    1    4
[2,]    2    1
[3,]    3    2
 >


Thus in this case f(a,d) gives a[,,1,2].   Function f() is necessary because
you specified that the length of 'd' is not known in advance.

You can get 'd' from a single row of expand.grid() [but you will have to
coerce it to a matrix]

HTH

rksh