[R] Filling matrices
Sarah Goslee
sarah.goslee at gmail.com
Mon Mar 19 22:21:54 CET 2012
I suspect I'm misinterpreting what you are trying to do, because it
seems unlikely that the solution is as simple as:
A <- matrix(0, 20, 20)
iRows <- c(2,3,4,6,7,8,10,11,12,14,15,16,18,19)
iCols <- c(1,2,3,5,6,7,9,10,11,13,14,15,17,18)
A[iRows, iCols] <- 1 # or a vector of the same length in the same order
So if that's not it, can you expand a bit on what your desired result
looks like?
Sarah
On Mon, Mar 19, 2012 at 5:07 PM, David Stevens <david.stevens at usu.edu> wrote:
> I'm a bit clumsy about many things in R. Here's my problem. I'm trying to
> build a square sparse matrix and populate it without looping (bad practice,
> right). I have vectors of matched row/column pairs for which the matrix
> entries have common characteristics and am look for a way to fill the
> entries. So, if the matrix is A[20 by 20], and I might have rows
>
> iRows <- c(2,3,4,6,7,8,10,11,12,14,15,16,18,19)
>
> and columns
>
> iCols <- c(1,2,3,5,6,7,9,10,11,13,14,15,17,18)
>
> and you see these are most of the subdiagonal terms in A from rows 2-19.
> They are all calculated in a similar way using values from a data frame in
> which the terms are generally in iRows and iCols.
>
> I could loop through each pair and all's well, but my question is whether
> there's an R-certified alternative, that will speed things up when the
> matrix is much larger (it will be - this is a prototype).
>
> Any thoughts?
>
> David S
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list