27

我有一个mat500 行 × 335 列的二维矩阵和一个 120425行的datdata.frame。data.framedat有两列IJ,它们是用于索引行、列的整数mat。我想将值添加matdat.

这是我的概念失败:

> dat$matval <- mat[dat$I, dat$J]
Error: cannot allocate vector of length 1617278737

(我在 Win32 上使用 R 2.13.1)。再深入一点,我发现我在滥用矩阵索引,因为我似乎只得到 的子矩阵mat,而不是我预期的一维值数组,即:

> str(mat[dat$I[1:100], dat$J[1:100]])
 int [1:100, 1:100] 20 1 1 1 20 1 1 1 1 1 ...

我期待类似的东西int [1:100] 20 1 1 1 20 1 1 1 1 1 ...。使用行、列索引来索引二维矩阵以获取值的正确方法是什么?

4

4 回答 4

42

几乎。需要作为两列矩阵提供给“[”:

dat$matval <- mat[ cbind(dat$I, dat$J) ] # should do it.

有一个警告:虽然这也适用于数据帧,但它们首先被强制转换为矩阵类,如果有任何非数字,则整个矩阵将成为“最小分母”类。

于 2011-08-03T01:12:30.640 回答
10

正如 DWin 所建议的那样,使用矩阵进行索引当然要干净得多,但由于某些奇怪的原因,使用 1-D 索引手动进行实际上会稍微快一些:

# Huge sample data
mat <- matrix(sin(1:1e7), ncol=1000)
dat <- data.frame(I=sample.int(nrow(mat), 1e7, rep=T), 
                  J=sample.int(ncol(mat), 1e7, rep=T))

system.time( x <- mat[cbind(dat$I, dat$J)] )     # 0.51 seconds
system.time( mat[dat$I + (dat$J-1L)*nrow(mat)] ) # 0.44 seconds

dat$I + (dat$J-1L)*nrow(m)部分将二维索引转换为一维索引。这1L是指定整数而不是双精度值的方法。这避免了一些强制。

...我还尝试了 gsk3 的基于应用的解决方案。虽然它慢了近 500 倍:

system.time( apply( dat, 1, function(x,mat) mat[ x[1], x[2] ], mat=mat ) ) # 212
于 2011-08-03T00:59:47.090 回答
1

这是使用apply基于行的操作的单线

> dat <- as.data.frame(matrix(rep(seq(4),4),ncol=2))
> colnames(dat) <- c('I','J')
> dat
   I  J
1  1  1
2  2  2
3  3  3
4  4  4
5  1  1
6  2  2
7  3  3
8  4  4
> mat <- matrix(seq(16),ncol=4)
> mat
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

> dat$K <- apply( dat, 1, function(x,mat) mat[ x[1], x[2] ], mat=mat )
> dat
  I J  K
1 1 1  1
2 2 2  6
3 3 3 11
4 4 4 16
5 1 1  1
6 2 2  6
7 3 3 11
8 4 4 16
于 2011-08-03T01:07:17.307 回答
0
n <- 10
mat <- cor(matrix(rnorm(n*n),n,n))
ix <- matrix(NA,n*(n-1)/2,2)
k<-0
for (i in 1:(n-1)){
    for (j in (i+1):n){
    k <- k+1
    ix[k,1]<-i
    ix[k,2]<-j
    }
}
o <- rep(NA,nrow(ix))
o <- mat[ix]
out <- cbind(ix,o)
于 2015-02-27T10:45:55.797 回答