[R] Reshape a sparse matrix

Scott Hyde hydes at byuh.edu
Wed May 16 07:43:47 CEST 2007

I wrote a function to reshape a sparse matrix of type dgTmatrix

It is as follows:

reshape.matrix <- function(A,r,c) {
  ## Reshape a matrix from the Matrix package
  ## of type dgTmatrix
  r_old <- A at Dim[1]
  c_old <- A at Dim[2]

  if(as.numeric(r_old*c_old) != as.numeric(r*c))
    stop("Invalid dimension.  There must be ",r_old*c_old," elements in the new matrix")
  k <- r_old*A at j + A at i
  i <- k %% r
  j <- (k-i)/r

  ## redo spMatrix so I don't have to add one to i and j
  dim <- c(as.integer(r), as.integer(c))
  new("dgTMatrix", x = A at x, Dim = dim,
      i = as.integer(i),
      j = as.integer(j))


Any suggestions on improvements of checks that I am missing?


More information about the R-help mailing list