Skip to content
Prev 307438 / 398506 Next

Convert COLON separated format

Matrix::spMatrix can help.

Read your data file with lns <- readLines("fileName") to get
something like
   lns <- c("1 5:15 7:17 9:19",
                 "2 2:22 8:28",
                 "4 6:46")
Then use a function like the following that reformats the
data to the i=row,j=col,x=value vectors that spMatrix can use.
   f <- function(lns, nrow=NULL, ncol=NULL)
   {
      # expect lines of the form "rowNum<whiteSpace>colNum:value[<whiteSpace>colNum:value ...]"
      triples <- unlist(lapply(strsplit(lns, "[ \t]+"), function(ln)paste(sep=":",ln[1],ln[-1]))))
      triples <- strsplit(triples, ":")
      if (any(which <- vapply(triples, length, 0) != 3)) stop("formatting error")
      ijx <- matrix(as.numeric(unlist(triples)), ncol=3, byrow=TRUE)
      if (is.null(nrow)) nrow <- max(ijx[,1])
      if (is.null(ncol)) ncol <- max(ijx[,2])
      spMatrix(nrow=nrow, ncol=ncol, i=ijx[,1], j=ijx[,2], x=ijx[,3])
   }
Use it as
4 x 9 sparse Matrix of class "dgTMatrix"

[1,] .  . . . 15  . 17  . 19
[2,] . 22 . .  .  .  . 28  .
[3,] .  . . .  .  .  .  .  .
[4,] .  . . .  . 46  .  .  .

or, if you know the number of rows and columns, tell it:
10 x 10 sparse Matrix of class "dgTMatrix"

 [1,] .  . . . 15  . 17  . 19 .
 [2,] . 22 . .  .  .  . 28  . .
 [3,] .  . . .  .  .  .  .  . .
 [4,] .  . . .  . 46  .  .  . .
 [5,] .  . . .  .  .  .  .  . .
 [6,] .  . . .  .  .  .  .  . .
 [7,] .  . . .  .  .  .  .  . .
 [8,] .  . . .  .  .  .  .  . .
 [9,] .  . . .  .  .  .  .  . .
[10,] .  . . .  .  .  .  .  . .

Use as.matrix() on its output if you don't want to continue
using the sparse matrix format.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com