s-news
[Top] [All Lists]

Re: Replacing values of one matrix from another

To: s-news@lists.biostat.wustl.edu, yves.claveau@mnr.gov.on.ca
Subject: Re: Replacing values of one matrix from another
From: Ray Brownrigg <Ray.Brownrigg@mcs.vuw.ac.nz>
Date: Wed, 19 Dec 2001 10:16:11 +1300 (NZDT)
> Windows NT 4 and I am stuck with a problem. I want to replace values in a
> matrix from values in a smaller one. I have:
> 
> dataa
> 
> tree  dbh     ht      tag
> 1     12      7       0
> 2     15      9       0
> 3     18      12      0
> 4     10      5       0
> 5     21      14      0
> 
> and
> 
> subplot
> 
> tree  tag
> 1     1
> 4     1
> 
> and I want to have
> 
> dataa
> 
> tree  dbh     ht      tag
> 1     12      7       1
> 2     15      9       0
> 3     18      12      0
> 4     10      5       1
> 5     21      14      0
> 
You could use matrix indexing.  Depending on how generalised you want
this, build on the following, which assumes subplot has only 2 columns,
but does not assume that dataa[, "tree"] is a complete sequence.

> whichrow <- match(subplot[, 1], dataa[, dimnames(subplot)[[2]][1]])
> whichcol <- which(dimnames(dataa)[[2]] == dimnames(subplot)[[2]][2])
> nrow <- dim(subplot)[1]
> indices <- matrix(c(whichrow, rep(whichcol, nrow)), nrow=nrow)
> dataa[indices] <- subplot[, 2]

Hope this helps,
Ray Brownrigg <ray@mcs.vuw.ac.nz>       http://www.mcs.vuw.ac.nz/~ray

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