[R] Array indexing

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Mar 26 21:05:33 CET 1999


John Logsdon <j.logsdon at lancaster.ac.uk> writes:

> a<-kronecker(1:4,t(11:15)) # Gives 4x5 matrix with unique elements
> 
> # 11 12 13 14 15
> # 22 24 26 28 30
> # 33 36 39 42 45
> # 44 48 52 56 60
> 
> b<-c(1,2,4,5)                 # The columns to extract for each of 4 rows
> z<-a[,b]                      # Gives a 4x4 matrix 
> 
> # 11 12 14 15
> # 22 24 28 30
> # 33 36 42 45
> # 44 48 56 60
> 
> ie a[1:4,b]
> 
> The only way I can see of getting the vector result I want is:
> 
> z<-rep(0,4);for (i in 1:4){z[i]<-a[i,b[i]]}
> 
> # 11 24 42 60
> 

Well, there's diag(a[,b]) or sapply(1:4,function(i)a[i,b[i]]) or
(double-UGH!! but efficient) Fortran style a[(b-1)*nrow(a)+1:4]

(And probably an obvious one that I've forgotten for the moment...)

-- 
   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
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list