tan*_*tan 5 statistics r matrix sparse-matrix
我有一个稀疏矩阵A,作为glmnet函数的输出生成.当我打印矩阵A时,它显示所有条目,并在顶部显示 -
1897 x 100 sparse Matrix of class "dgCMatrix"
[[ suppressing 32 column names 's0', 's1', 's2' ... ]]
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试查看矩阵的尺寸时,它显示为NULL:
> dim(A)
NULL
Run Code Online (Sandbox Code Playgroud)
因此,如果我使用as.matrix将其转换为常规矩阵并写入文件,我会收到错误:
as.matrix(fit$A[,1])
Error in as.matrix(fit$A[, 1]) :
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Error in fit$A[, 1] : incorrect number of dimensions
Run Code Online (Sandbox Code Playgroud)
如何获取此稀疏矩阵中的值并写入文件?
当我在glmnet函数中进行多项式回归(family ="multinomial")时,我遇到了这个问题.但是,当我进行binomail回归(family ="binomial")时,这种方法很好.
另外,我尝试过使用writeMM函数.这也不起作用:
> library('Matrix')
> writeMM(fit$A,file='test.txt')
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function 'writeMM' for signature '"list"'
Run Code Online (Sandbox Code Playgroud)
您可以使用writeMM和readMM读取和写入稀疏矩阵,因此无需将其强制转换为矩阵.
writeMM(fit$A,file='test.txt')
readMM(file='test.txt')
Run Code Online (Sandbox Code Playgroud)
编辑内multinomial,glmnet返回系数列表.因此,您需要遍历此列表并编写每个系数.这是一个例子:
library(glmnet)
g4=sample(1:4,100,replace=TRUE)
fit3=glmnet(x,g4,family="multinomial")
lapply(seq_along(fit3$beta),function(x)
writeMM(fit3$beta[[x]],file=paste0('coef.beta',x,'.txt')))
Run Code Online (Sandbox Code Playgroud)