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

______________________________________________
R-help@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.

Reply via email to