s-news
[Top] [All Lists]

Re: Extracting Elements from a matrix

To: "Ilouga, Pierre" <Pierre.Ilouga@evotec.com>, s-news@lists.biostat.wustl.edu
Subject: Re: Extracting Elements from a matrix
From: "Greg Snow" <Greg.Snow@intermountainmail.org>
Date: Wed, 7 Nov 2007 12:05:02 -0700
In-reply-to: <872D12160996E34584346FAF67F200E8027862@ge-ham-sma01.germany.evotecoai.com>
References: <872D12160996E34584346FAF67F200E8027862@ge-ham-sma01.germany.evotecoai.com>
Thread-index: AcghYUBt53Q3oqr2RyWEATzTh8bRugAD7u8w
Thread-topic: [S] Extracting Elements from a matrix
Is this what you are looking for?
 
> mat <- matrix(1:15, nrow=5, byrow=F)
> mat
     [,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15
> pos <- c(2, 1, 3, 3, 1)
> mat[ cbind(1:5, pos) ]
[1]  6  2 13 14  5
 
The key is to subscript using a matrix (not multiple vectors) with the 1st column representing all the rows and the 2nd the columns from those rows.
 
Hope this helps,
 

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow@intermountainmail.org
(801) 408-8111

 


From: s-news-owner@lists.biostat.wustl.edu [mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Ilouga, Pierre
Sent: Wednesday, November 07, 2007 10:12 AM
To: s-news@lists.biostat.wustl.edu
Subject: [S] Extracting Elements from a matrix

Dear Splus experts,

Does anyone has an idea how to extract some elements from a matrix in an EFFICIENT way? The following example clarifies  my question.

Given a  5x3 matrix  mat <- matrix(1:15, nrow=5, byrow=F)  and a length 5 -vector  of positions  pos <- c(2, 1, 3, 3, 1), the goal is to extract the vector c(6, 2, 13, 14, 5) which  corresponds to the column pos[j]  (j in 1:3) and row i  ( i in 1:5) without using for-loops and other memory consuming functions.

I?ve solve it via lists. However the slowness of the command executions doesn?t make it useful for  monte carlo simulation.

Thanks in advance.

PI

S-PLUS : Copyright (c) 1988, 2002 Insightful Corp.

S : Copyright Lucent Technologies, Inc.

Version 6.1.2 Release 2 for Linux 2.2.12 : 2002

Working data will be in .Data


Dr. Pierre Ilouga

Screening Operations/Discovery Informatics

EVOTEC AG

Schnackenburgallee 114

22525 Hamburg

Germany

pierre.ilouga@evotec.com

www.evotec.com

                   

Evotec AG Hamburg. Amtsgericht Hamburg HRB 68223
Vorstand: Jörn Aldag (Vorsitzender)
Aufsichtsratsvorsitzender: Prof. Dr. Dr. h.c. mult. Heinz Riesenhuber

<Prev in Thread] Current Thread [Next in Thread>