[R] "diag", "diag<-" and "[" , "[<-"

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jan 7 15:47:43 CET 2010


On 07/01/2010 9:31 AM, bergarog at gmail.com wrote:
> Dear all
> I have the following problem.
>
> M <- matrix(0,3,3) # dimension of M is dinamic and this can lead to the  
> next subscript
>
> diag(M[1,1]) <- rep(100,1)
> #Error in `diag<-`(`*tmp*`, value = 100) :
> # only matrix diagonals can be replaced
>
> diag(M[1,1,drop=F]) <- rep(100,1)
> #Error in diag(M[1, 1, drop = F]) <- rep(100, 1) :
> # incorrect number of subscripts
>
> diag(M[2:3,1:2]) <- rep(100,2)
> # works fine
>
> Is there a way to usw diag as replacement function when the input matrix is  
> subscript to a one by one matrix. I don't want extra if(dim==1)... etc.
>   

The problem isn't with diag, it's with "[<-".  When you include drop=F, 
it doesn't appear to handle properly the matrix indexing that diag() uses.

So a simpler example is just

M[1,1, drop=FALSE] <- 1

which generates the same error you saw.  I'd call this a bug; I'll look 
into it.  ("[<-" is done internally in some fairly ugly code, so this 
might take a while.)

As a workaround, I think this does what you want:

n <- 1
submatrix <- M[1:n,1:n,drop=FALSE]
diag(submatrix) <- rep(100, n)
M[1:n,1:n] <- submatrix

Duncan Murdoch

> Thanks a lot in advance.
> Best regards,
> Roger
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list