2
votes

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.

2
Check library slam.r.user.05apr

2 Answers

6
votes

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>)

1
votes

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)))