R相当于Matlab间谍功能

R equivalent of the Matlab spy function

Matlab中有一个名为spy的函数,可以显示稀疏矩阵的结构。它创建了一个矩阵维度图,其中每个具有非零值的条目都被着色。 R 中是否有等效函数?

image() 来自 Matrix 是一个选项。

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)


要在 R 中获得 spy() 的输出,需要多做一些工作。

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

在 R 中:

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

基于上述思想,在 R 中复制 Matlab spy() 函数的一个简单函数是:

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

这可能对某些应用程序有用。