[R] Generalising to n-dimensions
Robin Hankin
rksh1 at cam.ac.uk
Tue Sep 23 12:41:30 CEST 2008
Laura Bonnett wrote:
> crosstable[,,expand[d,1],expand[d,2],expand[d,3],...expand[d,n]]
>
> crosstable is just a crosstabulation of an n+2-dimensional dataset and
> I am trying to pick out those that are in combination 'd' of expand.
> So for example, for 5-dimensional data using your example:
>
> 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
>
> d refers to the row of the matrix above - d=2 is 2,1,1 so
> crosstable[,,2,1,1] would retrieve all the data where Var1 =2, Var2=1,
> Var3=1 and the two remaining variables are given in the
> crosstabulations for all values.
>
> Is that any better?
>
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
--
Robin K. S. Hankin
Senior Research Associate
Cambridge Centre for Climate Change Mitigation Research (4CMR)
Department of Land Economy
University of Cambridge
rksh1 at cam.ac.uk
01223-764877
More information about the R-help
mailing list