R:稀疏矩阵中的有效列减法

时间:2016-03-15 09:39:44

标签: r performance sparse-matrix subtraction

在这个稀疏矩阵中

#include <algorithm>
#include <iostream>
#include <vector>


struct Region {
    Region(int first, int count, int n):
        first(first),
        count(count),
        n(n)
    {

    }

    int first;
    int count;
    int n; // think struct Metadata
};


struct Comp
{
    inline bool operator()(const Region &region, int index) const
    {
        return region.first < index;
    }

    inline bool operator()(int index, const Region &region) const
    {
        return index < region.first;
    }
};


int main() {
    std::vector<Region> regions;
    regions.emplace_back(0, 10, 1);
    regions.emplace_back(10, 10, 2);
    regions.emplace_back(20, 10, 3);

    const int lookup = 10;

    auto iter = std::upper_bound(
        regions.begin(),
        regions.end(),
        lookup,
        Comp());

    // yes, I omitted error checking here, with error being iter == regions.begin()
    std::cout << lookup << " is in region with n = " << (iter-1)->n << std::endl;
}

如何最有效地从t?的值中减去t-1处的值?

这样可以将结果存储在矩阵D:

library(Matrix)
m <- matrix(c(1,3,1,2,2,3,1,1,2,2,3,4,1,1,2,1,1,2), nrow = 6)
M <- sparseMatrix(i = m[,1], j = m[,2], x = m[,3], dimnames = list(expression(x1, x2, x3), expression(t1, t2, t3, t4)))
M
3 x 4 sparse Matrix of class "dgCMatrix"
   t1 t2 t3 t4
x1  1  2  .  .
x2  .  1  1  .
x3  1  .  .  2

但这是最有效的方法吗?

使用摘要m可能效率更高吗?

P.S。:D [2,3]理想地读取&#34; 0&#34;而不是&#34;。&#34;。我怎么能得到它?

2 个答案:

答案 0 :(得分:2)

可能有快捷方式,但一种方法是创建一个正确大小的空稀疏矩阵;

> D = Matrix(0, dim(M)[1], dim(M)[2], sparse=TRUE, dimnames=dimnames(M))

# 3 x 4 sparse Matrix of class "dgCMatrix"
#    t1 t2 t3 t4
# x1  .  .  .  .
# x2  .  .  .  .
# x3  .  .  .  .

...并填充差异;

> D[,2:ncol(D)] = M[,2:ncol(M)] - M[,1:ncol(M)-1]

# 3 x 4 sparse Matrix of class "dgCMatrix"
#    t1 t2 t3 t4
# x1  .  1 -2  .
# x2  .  1  . -1
# x3  . -1  .  2

答案 1 :(得分:2)

另一个选择是cbind第一个空列:

empty_col_1 <- Matrix(0, nrow = nrow(M), ncol = 1, 
                      dimnames = list(NULL, "t1"))
D <- cbind(empty_col_1, M[, -1] - M[, -ncol(M)])