[R] hidden for() loop subsetting a matrix?
R. Michael Weylandt
michael.weylandt at gmail.com
Thu Aug 16 05:54:14 CEST 2012
On Wed, Aug 15, 2012 at 5:32 AM, Federico Calboli
<f.calboli at imperial.ac.uk> wrote:
> Hi,
>
> I am subsetting a matrix thus:
>
> test
> [,1] [,2] [,3]
> [1,] 1 7 13
> [2,] 2 8 14
> [3,] 3 9 15
> [4,] 4 10 16
> [5,] 5 11 17
> [6,] 6 12 18
>
> test[cbind(c(1,3,5), c(2,1,3))]
> [1] 7 3 17
>
> This works fine, and is the equivalent of c(test[1,2], test[3,1], test[5,3]). cbind(c(1,3,5), c(2,1,3)) would obviously look like:
>
> [,1] [,2]
> [1,] 1 2
> [2,] 3 1
> [3,] 5 3
>
>
> My question is, since the subsetting is effectively extracting the values by taking one line at a time in the cbind() coordinates matrix, is a for() loop at work here? Or is the subsetting action doing something smarter than just extracting each value reading one set of coordinates at a time? This is purely an academic question, but I'm very curious about the answer.
Canonically, see
$(R_HOME)/src/main/subset.c
lines 159ff and
$(R_HOME)/src/main/subscript.c
lines 316ff.
More directly, R does something akin to arrayInd() but at the C level
-- so yes, a for loop, but a good one ;-) -- and then regular
subsetting.
Cheers,
Michael
>
> Best wishes,
>
> Federico
>
>
>
> --
> Federico C. F. Calboli
> Neuroepidemiology and Ageing Research
> Imperial College, St. Mary's Campus
> Norfolk Place, London W2 1PG
>
> Tel +44 (0)20 75941602 Fax +44 (0)20 75943193
>
> f.calboli [.a.t] imperial.ac.uk
> f.calboli [.a.t] gmail.com
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list