2

Might be a very silly question, but I cannot seem to find a proper way to create a sparse diagonal matrix in R. I've found the functions:

  • diag.spam()
  • spdiags()

and used them with library Matrix and package spam downloaded, but R did not seem to recognize these functions. Does anyone know a function or library I need to download?

I need it because I want to create diagonal matrices larger than 256 by 256.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Britta
  • 135
  • 1
  • 1
  • 8

2 Answers2

6

The Diagonal() function in the Matrix package. (Matrix is a "recommended" package, which means it is automatically available when you install R.)

library(Matrix)
m <- Diagonal(500)
image(m)

Diagonal(n) creates an n x n identity matrix. If you want to create a diagonal matrix with a specified diagonal x, use Diagonal(x=<your vector>)

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
1

Use bandSparse of the Matrix library.

to get an n-by-n matrix with m on its diagonal use, write:

bandSparse(n,n,0,list(rep(m, n+1)))
Britta
  • 135
  • 1
  • 1
  • 8