[R] Creating a sparse matrix from a file

David Winsemius dwinsemius at comcast.net
Tue Oct 27 00:58:57 CET 2009


On Oct 26, 2009, at 5:06 AM, Pallavi Palleti wrote:

>
> Hi all,
>
> I am new to R and learning the same. I would like to create a sparse  
> matrix
> from an existing file whose contents are in the format
>      "rowIndex,columnIndex,value"
>
> for ex:
> 1,2,14
> 2,4,15
>
> I would like to create a sparse matrix by taking the above as input.
> However, I couldn't find an example where the data was being read  
> from a
> file. I tried searching in R tutorial and also searched for the same  
> in web
> but in vain. Could some one kindly help me how to give the above  
> format as
> input in R to create a sparse matrix.

  ex <- read.table(textConnection("1,2,14
  2,4,15") , sep=",")
  ex
#  V1 V2 V3
#1  1  2 14
#2  2  4 15

  M <- Matrix(0, 20, 20)

 > M
#20 x 20 sparse Matrix of class "dsCMatrix"

  [1,] . . . . . . . . . . . . . . . . . . . .
  [2,] . . . . . . . . . . . . . . . . . . . .
  [3,] . . . . . . . . . . . . . . . . . . . .
snip

  for (i in 1:nrow(ex) ) { M[ex[i, 1], ex[i, 2] ] <- ex[i, 3] }

 > M
20 x 20 sparse Matrix of class "dgCMatrix"

  [1,] . 14 .  . . . . . . . . . . . . . . . . .
  [2,] .  . . 15 . . . . . . . . . . . . . . . .
  [3,] .  . .  . . . . . . . . . . . . . . . . .
snip
 >
--

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list