Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab's sparse(i,j,s,m,n) equivalent in R

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)

like image 581
pablete Avatar asked Dec 27 '22 01:12

pablete


2 Answers

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.

set.seed(1)
n=50
x <- sample(seq(100), n)
y <- sample(seq(100), n)
z <- runif(n)
cbind(x,y,z)

library(Matrix)
s.mat <- sparseMatrix(i=x, j=y, x=z)
dim(s.mat)
image(s.mat)

#convert to a class matrix if needed
mat <- as.matrix(s.mat)
mat[which(mat==0)] <- NaN

enter image description here

like image 85
Marc in the box Avatar answered Jan 05 '23 19:01

Marc in the box


The Matrix package offers a variety of sparse matrix classes. After a sparse matrix object is created you would load the values in precisely the manner you describe above:

library(Matrix)
?Matrix

... will get you started. By the way, the code for loading a dense matrix in the manner you illustrated would be:

M <- matrix(NA, nrow=max(c(IND1,IND2)), ncol=max(c(IND1,IND2)) ) # could use higher numbers
M[ cbind(IND1, IND2) ] <- VAL
like image 32
IRTFM Avatar answered Jan 05 '23 17:01

IRTFM