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] <- valsBut 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
Duncan Murdoch
2009-Jun-11 17:28 UTC
[R] Syntax question: assigning sparse matrix elements
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
Possibly Parallel Threads
- Unicode support--case sensitive in share name
- crash problem when using IndirectBrInst to replace BranchInst
- [virtio-dev] packed ring layout proposal - todo list
- [virtio-dev] packed ring layout proposal - todo list
- crash problem when using IndirectBrInst to replace BranchInst