Re: [R] how ot replace the diagonal of a matrix

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Tue 03 Oct 2006 - 21:23:48 GMT

Duncan Murdoch <murdoch@stats.uwo.ca> writes:

> On 10/3/2006 4:59 PM, roger bos wrote:
> > Dear useRs,
> >
> > Trying to replace the diagonal of a matrix is not working for me. I
> > want a matrix with .6 on the diag and .4 elsewhere. The following
> > code looks like it should work--when I lookk at mps and idx they look
> > how I want them too--but it only replaces the first element, not each
> > element on the diagonal.
> >
> > mps <- matrix(rep(.4, 3*3), nrow=n, byrow=TRUE)
> > idx <- diag(3)
> > mps
> > idx
> > mps[idx] <- rep(.6,3)
> >
> > I also tried something along the lines of diag(mps=.6, ...) but it
> > didn't know what mps was.
>
> Matrix indexing can use a two column matrix, giving row and column
> numbers. So you could get what you want by
>
> mps[cbind(1:n,1:n)] <- 0.6

Or even diag(mps) <- 0.6

(this *is* displayed quite prominently on help(diag)!)

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@stat.math.ethz.ch 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.
Received on Wed Oct 04 08:02:45 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 03 Oct 2006 - 22:30:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.