gpt4 book ai didi

R 将矩阵或数据框转换为 sparseMatrix

转载 作者:行者123 更新时间:2023-12-03 08:55:38 24 4
gpt4 key购买 nike

我有一个常规矩阵(非稀疏),我想将其转换为 sparseMatrix (使用 Matrix 包)。有没有一个函数可以做到这一点,还是我需要做一堆循环?

前任。

> regMat <- matrix(0, nrow=10, ncol=10)
> regMat[3,5] <- round(runif(1),2)*100
> regMat[2,8] <- round(runif(1),2)*100
> regMat[8,4] <- round(runif(1),2)*100
> regMat[1,6] <- round(runif(1),2)*100
> regMat[7,4] <- round(runif(1),2)*100
> regMat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 49 0 0 0 0
[2,] 0 0 0 0 0 0 0 93 0 0
[3,] 0 0 0 0 20 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 8 0 0 0 0 0 0
[8,] 0 0 0 14 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0

有什么建议?

最佳答案

这里有两个选项:

library(Matrix)

A <- as(regMat, "sparseMatrix") # see also `vignette("Intro2Matrix")`
B <- Matrix(regMat, sparse = TRUE) # Thanks to Aaron for pointing this out

identical(A, B)
# [1] TRUE
A
# 10 x 10 sparse Matrix of class "dgCMatrix"
#
# [1,] . . . . . 45 . . . .
# [2,] . . . . . . . 59 . .
# [3,] . . . . 95 . . . . .
# [4,] . . . . . . . . . .
# [5,] . . . . . . . . . .
# [6,] . . . . . . . . . .
# [7,] . . . 23 . . . . . .
# [8,] . . . 63 . . . . . .
# [9,] . . . . . . . . . .
# [10,] . . . . . . . . . .

关于R 将矩阵或数据框转换为 sparseMatrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10555210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com