[R] re placing values in a matrix

Gabor Csardi csardi at rmki.kfki.hu
Fri Feb 1 14:57:16 CET 2008


Derek, 

the 0*m part zeros out everything in the matrix, expect for the NA's, 
0*NA=NA by definition. If we add this to the y[ col(m) ] matrix, then
NA+anything=NA, but 0+anything=anything.

G.

ps. please answer to the list (as well)

On Fri, Feb 01, 2008 at 08:52:50AM -0500, Derek Cyr wrote:
> 
> 
> Thank you, that works very nicely.  I am a little curious as to why you
> need to do 0*m and add that to y[col(m)] in the second expression.  It
> works perfectly, but I am just not sure how, lol.  Thanks
> 
> D

[...]

> Actually, you don't need apply. If there are no NA's then it is
> very easy:
> 
> m[] <- y[ col(m) ]
> 
> If you want to keep the NA's then it is a bit more tricky:
> 
> m[] <- 0*m + y[ col(m) ]
> 
> 
> G.
> 
> On Thu, Jan 31, 2008 at 07:03:51PM -0800, dxc13 wrote:
> >
> > useR's,
> >
> > Consider:
> > y <- c(20, 25, 30)
> > > m <- matrix(c(0.0,1,NA,0.5,1.25,0.75, 0.5, NA,
> > > NA),byrow=TRUE,nrow=3,ncol=3)
> > > m
> >      [,1] [,2] [,3]
> > [1,]  0.0 1.00   NA
> > [2,]  0.5 1.25 0.75
> > [3,]  0.5   NA   NA
> >
> > For each numeric value, I want to replace them with their corresponding
> > y-value.  The result should look like (here, each row represents a
> variable
> > rather than the columns):
> >       [,1] [,2] [,3]
> > [1,]  20   25   NA
> > [2,]  20   25   30
> > [3,]  20  NA   NA
> >
> > Does anyone know how I can do this using apply()?  Or is there an easier
> > way?  Thanks in advance.
> >
> > Derek
> > --
> > View this message in context:
> http://www.nabble.com/replacing-values-in-a-matrix-tp15219764p15219764.html
> > Sent from the R help mailing list archive at Nabble.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.
> 
> --
> Csardi Gabor <csardi at rmki.kfki.hu>    UNIL DGM
> 
> 
> 
> IMPORTANT NOTICE:  This e-mail and any attachments may contain confidential or sensitive information which is, or may be, legally privileged or otherwise protected by law from further disclosure.  It is intended only for the addressee.  If you received this in error or from someone who was not authorized to send it to you, please do not distribute, copy or use it or any attachments.  Please notify the sender immediately by reply e-mail and delete this from your system. Thank you for your cooperation.
> 

-- 
Csardi Gabor <csardi at rmki.kfki.hu>    UNIL DGM



More information about the R-help mailing list