[R] Array indexing
Bill Venables
wvenable at arcola.stats.adelaide.edu.au
Sat Mar 27 03:30:54 CET 1999
>>>>> "Peter" == Peter Dalgaard BSA <p.dalgaard at biostat.ku.dk> writes:
Peter> John Logsdon <j.logsdon at lancaster.ac.uk> writes:
>> 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
>>
Peter> Well, there's diag(a[,b]) or
Peter> sapply(1:4,function(i) a[i, b[i]]) or (double-UGH!! but
Peter> efficient) Fortran style a[(b-1)*nrow(a)+1:4]
Peter> (And probably an obvious one that I've forgotten for
Peter> the moment...)
Indeed there is and just about everyone does forget it:
> b <- c(1,2,4,5)
> z <- a[cbind(1:4, b)]
> z
[1] 11 24 42 60
You can also work it in the other direction:
> a
[,1] [,2] [,3] [,4] [,5]
[1,] 11 12 13 14 15
[2,] 22 24 26 28 30
[3,] 33 36 39 42 45
[4,] 44 48 52 56 60
> a[cbind(1:4, c(2,3,1,5))] <- 0
> a
[,1] [,2] [,3] [,4] [,5]
[1,] 11 0 13 14 15
[2,] 22 24 0 28 30
[3,] 0 36 39 42 45
[4,] 44 48 52 56 0
It's sometimes called a "matrix index" which can be a bit
confusing since the *index* is the matrix as well as the thing
it indexes (though the latter can be an arbitrary array).
Bill Venables.
--
The following contact details work now, but is only official
after 1/5/1999:
-----------------------------------------------------------------
Dr Bill Venables, Statistician, CMIS Environmetrics Project.
Physical address: Postal address:
CSIRO Marine Laboratories, PO Box 120,
233 Middle St, Cleveland, Queensland Cleveland, Qld, 4163
AUSTRALIA AUSTRALIA
Telephone: +61 7 3826 7200 Email: Bill.Venables at cmis.csiro.au
Fax: +61 7 3826 7304
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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