[R] aperm() and as.list() args to "["

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Mar 10 15:48:54 CET 2004


[Ooops. Forgot to copy the list 1st time around... Also missed the
possibility of using t()]

Robin Hankin <rksh at soc.soton.ac.uk> writes:

> Hi everyone.
> 
> I'm playing with aperm():
> 
> a <- 1:24
> dim(a) <- c(2,3,2,2)
> permutation <-  c(1,2,4,3)
> b <- aperm(a,permutation)
> 
> 
> So if my understanding is right,
> 
> a[1,3,2,1] ==  b[c(1,3,2,1)[permutation] ]
> 
> but this isn't what I want because the RHS evaluates to a vector, and
> I am trying to identify a single element of b.
> 
> How do I modify the RHS to give what I want?

Matrix indexing:

> a[1,3,2,1]
[1] 11
>  b[rbind(c(1,3,2,1)[permutation])]
[1] 11

or, equivalently:
>  b[matrix(c(1,3,2,1)[permutation],1)]
[1] 11

or (neat, once you get it)

>  b[t(c(1,3,2,1)[permutation])]
[1] 11


> Following aren't right  either:
> b[as.vector(c(1,3,2,1)[permutation]) ]
> b[as.list(c(1,3,2,1)[permutation]) ]
> 
> 
> OBattempt:
> eval(parse(text=paste("b[",paste(c(1,3,2,1)[permutation],collapse=","),"]")))
> 
> which DOES work, but is ghastly!

Less ghastly (but only slightly so):

> do.call("[",c(list(b),as.list(c(1,3,2,1)[permutation])))
[1] 11

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list