s-news
[Top] [All Lists]

Re: updating a matrix via coordinates

To: "'Robert Anthony Canales'" <rcanales@Stanford.EDU>
Subject: Re: updating a matrix via coordinates
From: "Venables, Bill (CMIS, Cleveland)" <Bill.Venables@CMIS.CSIRO.AU>
Date: Wed, 1 Aug 2001 13:44:38 +1000
Cc: s-news@lists.biostat.wustl.edu

>  -----Original Message-----
> From:         Robert Anthony Canales [mailto:rcanales@Stanford.EDU] 
> Sent: Wednesday, 1 August 2001 12:07 PM
> To:   s-news@lists.biostat.wustl.edu
> Subject:      [S] updating a matrix via coordinates
> 
> Hello,
> As a follow-up to a previous question, I have a dataframe with 2 columns:
> 
> add.value  code.coord
> 5            ABC
> 10           DEF
> 2            ABC
> 14           GHI
> .             .
> .             .
> 
> The code.coord are codes that represent coordinates of a larger matrix
> called large.matrix.  Each code (ABC, DEF, GHI) is a separate matrix of
> row and column values and each set of coordinates is a different element
> of a list (codes.list).  What I need to do is read the dataframe above,
> use the code in code.coord to access the coordinates stored in the
> codes.list and add the value of add.value to the large.matrix elements
> corresponding to the coordinates given by the code.  The end result is the
> large.matrix with the sum of all relevant add.values in particular
> elements of the matrix.
> 
> I have been able to perform this task for one row and I have a feeling
> I could evaluate all rows with a 'for' loop.  But in the interest of time,
> I would like to avoid looping through each row of the dataframe.  Do you
> have any ideas how to make this algorithm more efficient?

Your English is a little muddy, but if I have understood you correctly you
can do it as follows (asuming the data frame above is "dat"):

sums <- tapply(dat$add.value, dat$code.coord, sum)

for(j in names(sums)) 
        large.matrix[codes.list[[j]]] <- large.matrix[codes.list[[j]]] +
sums[j]


Working our why is left as an easy exercise for he reader.  This still has
one for() loop, but it's the minimal loop and for most problems it would be
an effective solution.  (With only an abstract version of the problem to go
on, though, it's very hard to say.)


> Thanks in advance,
> RC
> 
> ---------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu.  To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message:  unsubscribe s-news

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