I’m working with R.
I have a matrix structure but stored in three lists IND1, IND2, and VAL, each of the same length N; I need to store the values in VAl in a matrix MAT such that:
for each i in 1 to N:
MAT[IND1(i), IND2(i)] == VAL(i)
As you can guess the final size of MAT is not necessarily NxN, but I do know what the size must be (call it m if you need to know the size, since for me it must be a square matrix).
Matlab has a nice function to create a sparse matrix that does exactly this, but i need to accomplish this in the language R, hopefully without loops, does anyone know if this can be done and would please tell me how. Thanks in advance.
P.S: I’ve tried the obvious:
MAT <- matrix(nrow=m, ncol=m)
MAT[IND1, IND2] <- VAL
but I get a weird result (all rows have the same repeated value)
DWin is right – the Matrix package is the way to go. However, if you have a lot of data, I have found that the replacement type of value substitution can get hung up or take a long time. A better way might be to make a class sparseMatrix object and then convert to class matrix if needed. Ex.