[R] Syntax question: assigning sparse matrix elements

Dan Ruderman dlruderman at yahoo.com
Thu Jun 11 18:34:15 CEST 2009


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.

Regards
Dan




More information about the R-help mailing list