gpt4 book ai didi

R构建稀疏矩阵

转载 作者:行者123 更新时间:2023-12-01 02:21:41 25 4
gpt4 key购买 nike

我正在阅读 R 中 Matrix 包的说明。但我无法理解 p函数中的参数:

sparseMatrix(i = ep, j = ep, p, x, dims, dimnames,
symmetric = FALSE, index1 = TRUE,
giveCsparse = TRUE, check = TRUE)

根据 http://stat.ethz.ch/R-manual/R-devel/library/Matrix/html/sparseMatrix.html

p:
numeric (integer valued) vector of pointers, one for each column (or row), to the initial (zero-based) index of elements in the column (or row). Exactly one of i, j or p must be missing.



我想 p用于行或列索引的压缩表示,因为在 i 中包含多个元素是浪费的或 j具有相同的值来表示单个行/列。但是当我尝试提供的示例时,我仍然不知道如何 p正在控制 x 的哪个元素转到哪行/列
dn <- list(LETTERS[1:3], letters[1:5])
## pointer vectors can be used, and the (i,x) slots are sorted if necessary:
m <- sparseMatrix(i = c(3,1, 3:2, 2:1), p= c(0:2, 4,4,6), x = 1:6, dimnames = dn)

最佳答案

只需在 ?SparseMatrix 中往下读一点了解如何p被解释。 (特别要注意 p 的“扩展形式”。)

If ‘i’ or ‘j’ is missing then ‘p’ must be a non-decreasing integer vector whose first element is zero. It provides the compressed, or “pointer” representation of the row or column indices, whichever is missing. The expanded form of ‘p’, ‘rep(seq_along(dp),dp)’ where ‘dp <- diff(p)’, is used as the (1-based) row or column indices.



这是一个小函数,可以帮助您了解这在实践中的含义:
pex <- function(p) {
dp <- diff(p)
rep(seq_along(dp), dp)
}

## Play around with the function to discover the indices encoded by p.
pex(p = c(0,1,2,3))
# [1] 1 2 3

pex(p = c(0,0,1,2,3))
# [1] 2 3 4

pex(p = c(10,11,12,13))
# [1] 1 2 3

pex(p = c(0,0,2,5))
# [1] 2 2 3 3 3

pex(p = c(0,1,3,3,3,3,8))
# [1] 1 2 2 6 6 6 6 6

关于R构建稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20008200/

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