[R] Array indexing

John Logsdon j.logsdon at lancaster.ac.uk
Fri Mar 26 19:55:21 CET 1999


I want to pick out a single member for each row of a matrix according to
an indexing vector and I would have thought this was a simple operation. 

Is it that I am too stuck in Fortran for my own good (so wots rong with
fortran?), but is there a better way of doing what to me is intuitive but
gives completely the wrong answer.  The following result occurs: 

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

whereas a[1,b] returns

# 11 12 14 15

Mind you, the same happens in Octave!  Ugh.  Is there a more elegant way
without constructing the appropriate elementary matrix or am I mad?  These
are not exclusive possibilites of course! 

John

BTW the command element(x,i) which is in the HTML help for 0.63.3 is
missing.

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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