[R] Syntax question: assigning sparse matrix elements

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jun 11 19:28:36 CEST 2009


On 6/11/2009 12:34 PM, Dan Ruderman wrote:
> Hopefully this is straightfoward.
> 
> I have an matrix which is mostly zeroes.  I want to assign it
> some non-zero elements whose rows, columns, and values I know.
> 
> As a simple example, say I create a 3x2 matrix of zeros:
>> m <- matrix(rep(0,6),nrow=3)
> 
> Now say I want to make the [1,1] and [3,2] elements of this
> matrix be non-zer, so I create two vectors, one for rows and one for cols:
>> rows <- c(1,3)
>> cols <- c(1,2)
> 
> And I have two values to be put in these locations:
>> vals <- c(-1,1)
> 
> What I'd like to do is something like:
>> m[rows,cols] <- vals
> 
> But what I get instead is:
> 
>> m
>      [,1] [,2]
> [1,]   -1   -1
> [2,]    0    0
> [3,]    1    1
> 
> 
> What I hoped to see is:
> 
>> m
>      [,1] [,2]
> [1,]   -1    0
> [2,]    0    0
> [3,]    0    1
> 
> 
> If anyone can offer some advice I'd be most thankful.

If the index to a matrix is a two column matrix, then the first column 
is taken to be a row number, the second a column number.  So you get 
what you want with

m[cbind(rows,cols)] <- vals

This is discussed (and other indexing methods too) in the R Language 
Definition manual in the section on indexing matrices and arrays.

Duncan Murdoch




More information about the R-help mailing list