Re: [R] Array indexing

Bill Venables (wvenable@arcola.stats.adelaide.edu.au)
Sat, 27 Mar 1999 13:00:54 +1030 (CST)

From: Bill Venables <wvenable@arcola.stats.adelaide.edu.au>
Date: Sat, 27 Mar 1999 13:00:54 +1030 (CST)
To: Peter Dalgaard BSA <p.dalgaard@biostat.ku.dk>
Subject: Re: [R] Array indexing
In-Reply-To: <x2g16saueq.fsf@blueberry.kubism.ku.dk>
<x2g16saueq.fsf@blueberry.kubism.ku.dk>

>>>>> "Peter" == Peter Dalgaard BSA <p.dalgaard@biostat.ku.dk> writes:

Peter> John Logsdon <j.logsdon@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@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@stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._


This archive was generated by hypermail 1.02.