5

In Matlab, there is a function named spy, which displays the structure of a sparse matrix. It creates a plot of the matrix' dimensions where each entry that has a nonzero value is colored. Is there an equivalent function in R?

nojka_kruva
  • 1,454
  • 1
  • 10
  • 23
  • Can you include a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with a sample R object that you wish to plot? – MrFlick Apr 15 '15 at 16:09
  • As an aside, the Matlab `spy()` function includes a fun little feature that I'm sure won't be replicated in R. Try submitting `spy()` with no arguments in Matlab. – Alex A. Apr 15 '15 at 17:19
  • @alexforrence: Excellent. Absolutely excellent. – Alex A. Apr 15 '15 at 17:45

2 Answers2

8

image() from Matrix is one option.

library(Matrix)

# Example from ?Matrix:::sparseMatrix
i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)
A <- sparseMatrix(i, j, x = x)

print(A)
##8 x 10 sparse Matrix of class "dgCMatrix"

##[1,] . 7 . . .  .  .  .  .  .
##[2,] . . . . .  .  .  .  .  .
##[3,] . . . . .  .  .  . 14  .
##[4,] . . . . . 21  .  .  .  .
##[5,] . . . . .  . 28  .  .  .
##[6,] . . . . .  .  . 35  .  .
##[7,] . . . . .  .  .  . 42  .
##[8,] . . . . .  .  .  .  . 49

image(A)

enter image description here


To get the output of spy() in R, it takes a little bit more work.

In MATLAB (2011b):

spy()
h = gcf;
axObj = get(h, 'Children');
datObj = get(axObj, 'Children');

xdata = get(datObj,'XData');
ydata = get(datObj,'YData');
spyMat = [xdata; ydata];
csvwrite('spydat.csv',spyMat);

And in R:

library(Matrix)
spyData <- read.csv("spydat.csv")
spyMat <- t(sparseMatrix(spyData[1,],spyData[2,]))
image(spyMat)

enter image description here

alexforrence
  • 2,724
  • 2
  • 27
  • 30
0

A simple function that duplicates the Matlab spy() function in R, based on above ideas, is:

  library(Matrix)
  spy <- function(w){
    # Get indices not equal to zero
    inds <- which(w != 0, arr.ind=TRUE )
    # Create sparse matrix with ones where not zero
    A <- sparseMatrix(inds[,1], inds[,2], x = rep(1,nrow(inds)))
    # 
    image(A))
  }

This may be useful for some applications.

Graham G
  • 551
  • 5
  • 14