🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: aus.stats.s
Article #177

Re: extraction

#177
From: allan
Date: Tue, 12 Jan 1993 20:43
32 lines
1891 bytes
Snyder Hugh (larry@ai.mit.edu) asks about subscripting a 3-way array:

> 	> dim(Data)
> 	100 5 8
> 	> length( Index )
> 	100
> Here's what I'd like to do:
> 	> New <- array(NA, dim=c(100,5))
> 	> for (i in 1:100)
> 	     New[i,] <- Data[i,,Index[i] ]

Most (all?) S users know about subscripting arrays using multiple
indices (as many as there are dimensions).  Fewer (but probably still
many) know that if an array is subscripted with a single vector, the
array itself is treated as a vector (in "column-major" order), with the
subscript acting accordingly.  I think, however, that many people don't
know about subscripting an array with a matrix; hence, I'm sending this
to s-news rather that just to Mr. Hugh.

If an array is subscripted with a single matrix, and that matrix has as
many columns as the array has dimensions, then each row of the matrix
is used to select one element from the array, and the returned value is
a vector of the selected elements.  In Mr. Hugh's case, this matrix can
easily be constructed using cbind() and a few rep()s, and then the
result of the subscripting can be shaped into the desired matrix:

matrix(Data[cbind(rep(1:100,5), rep(1:5,rep(100,5)), rep(Index,5))], 100, 5)

(I think this is correct -- I didn't try it).  Notice that the matrix
subscript must be constructed with the "column-major" storage order of
arrays in mind, in order for the final reshaping to work.  This kind of
subscripting is documented: help('[').
Technical Details
Message-ID: <9301122043.AA16457@dmssyd.syd.dms.CSIRO.AU>
Path: arc1-ca.pugleaf.net!sparky!uunet!munnari.oz.au!metro!dmssyd.syd.dms.CSIRO.AU!news

Show Full Headers
Complete Article Headers
Newsgroups: aus.stats.s
Path: arc1-ca.pugleaf.net!sparky!uunet!munnari.oz.au!metro!dmssyd.syd.dms.CSIRO.AU!news
From: allan@research.att.com
Subject: Re: extraction
Message-ID: <9301122043.AA16457@dmssyd.syd.dms.CSIRO.AU>
X-Gateway: dmssyd.syd.dms.CSIRO.AU
Lines:  32
Sender: daemon@syd.dms.CSIRO.AU
Organization: CSIRO Div. Maths & Stats, CSIRO Div. Applied Physics
Date: Tue, 12 Jan 1993 20:43:38 GMT