我有一个2D矩阵mat
,有500行× 335列,和一个数据帧dat
,有120425行。数据帧dat
有两个列I
和J
,它们是整数,用于索引mat
的行、列。我想将mat
的值添加到dat
的行。
这是我的概念失败:
> 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 ...
之类的东西。什么是正确的方式来索引二维矩阵使用的行,列的索引来获得值?
差不多了。需要提供给"["作为两列矩阵:
dat$matval <- mat[ cbind(dat$I, dat$J) ] # should do it.
有一个警告:虽然这也适用于数据帧,但它们首先被强制为矩阵类,如果有非数字的,则整个矩阵成为"最小分母"类。
像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
下面是使用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
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)