3

我有一个索引矩阵,其中一些索引重复。我在下面举了一个例子。

我有另一个矩阵 A,其尺寸与索引兼容,并且在任何地方都初始化为 0。我想做类似的事情

A[I] += 1

我面临两个问题:

  1. A[I] = A[I] + 1效率太低
  2. 矩阵I有冗余索引。例如第 2 行和第 6 行是相同的,我想获得A[1,2] = 2

部分答案是创建一个 3 列矩阵,其中两列是的乘积,unique(I)第三列是计数的乘积,但我也没有看到任何解决方案。任何指针或帮助将不胜感激!

> I is:
     [,1] [,2]
[1,]    1    1
[2,]    1    2
[3,]    1    3
[4,]    1    4
[5,]    1    1
[6,]    1    2
[7,]    1    3
4

2 回答 2

3

这可能是使用稀疏矩阵方法最快的方法(参见 Matrix 包等)。

使用标准矩阵,您可以使用xtabs函数然后矩阵分配(根据评论编辑)折叠相同的行:

I <- cbind(1, c(1:4,1:3))

tmp <- as.data.frame(xtabs( ~I[,1]+I[,2] ))

A <- matrix(0, nrow=5, ncol=5)
tmp2 <- as.matrix(tmp[,1:2])
tmp3 <- as.numeric(tmp2)
dim(tmp3) <- dim(tmp2)
A[ tmp3 ] <- tmp[,3]
A

您可以通过将核心功能拉出as.data.frame.table而不是转换为数据框并再次返回来使其更快一点。

这是另一个可能更有效的版本。它将覆盖一些 0 与其他 0 计算xtabs

I <- cbind(1:5,1:5)
A <- matrix(0, 5, 5)

tmp <- xtabs( ~I[,2]+I[,1] )

A[ as.numeric(rownames(tmp)), as.numeric(colnames(tmp)) ] <- c(tmp)
A

如果 A 矩阵有 dimnames 并且 I 矩阵有名字而不是索引,那么后面的也可以工作(只需删除as.numerics.

于 2012-11-08T20:37:38.867 回答
2

干得好:

## Reproducible versions of your A and I objects
A <- matrix(0, nrow=2, ncol=5)
## For computations that follow, you'll be better off having this as a data.frame
## (Just use `I <- as.data.frame(I)` to convert a matrix object I).
I <- read.table(text=" 1    1
1    2
1    3
1    4
1    1
1    2
1    3", header=FALSE)

## Create data.frame with number of times each matrix element should
## be incremented
I$count <- ave(I[,1], I[,1], I[,2], FUN=length)
I <- unique(I)

## Replace desired elements, using a two column matrix (the "third form of
## indexing" mentioned in "Matrices and arrays" section" of ?"[").
A[as.matrix(I[1:2])] <- I[[3]]

A
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    2    2    1    0
# [2,]    0    0    0    0    0
于 2012-11-08T20:35:40.710 回答