-2

我有一个矩阵调用 res 最初如下所示:

      [,1] [,2]
[1,]     0    0
[2,]     0    0
[3,]     0    0
[4,]     0    0
[5,]     0    0
[6,]     0    0
[7,]     0    0
[8,]     0    0
[9,]     0    0
[10,]    0    0 

我有一个索引矩阵(索引),如下所示:

     [,1] [,2]
 [1,]   2    3
 [2,]   7    9

我希望得到的 res 矩阵如下所示:

      [,1] [,2]
[1,]     0    0
[2,]     1    1
[3,]     1    1
[4,]     0    0
[5,]     0    0
[6,]     0    0
[7,]     1    1
[8,]     1    1
[9,]     1    1
[10,]    0    0 

我有一个大矩阵,循环遍历索引矩阵需要很长时间。请让我知道是否有更好的方法来做到这一点。我希望做一些类似 mat[indexes,] <- 1 的事情。但是,这不起作用我想要的。

4

3 回答 3

2

如果res您的主矩阵 和indexes是索引矩阵:

这可能会有所帮助:

idx  <- do.call("c",apply(indexes,1,function(x){seq(x[1],x[2])}))

res[idx,] <- 1

至于时间,首先创建一个大索引矩阵:

> set.seed(42)
> indexes <- t(matrix(sort(sample(1:10000,1000)),2,500))
> head(indexes)
     [,1] [,2]
[1,]    3    4
[2,]   14   16
[3,]   23   33
[4,]   40   63
[5,]   67   74
[6,]   79   83

和时间:

> system.time(idx  <- do.call("c",apply(indexes,1,function(x){seq(x[1],x[2])})))   user  system elapsed 
  0.008   0.000   0.007 

> system.time( idx2 <- unlist( apply( indexes , 1 , FUN = function(x){ seq.int(x[1],x[2])}) ))
   user  system elapsed 
  0.004   0.000   0.002

看起来第二种方法稍微快一些。

于 2013-06-18T21:06:09.710 回答
0

编辑:我确实误解了,这应该会有所帮助:

test <- matrix(rep(0,1E7), ncol=2)
Index <- matrix(sort(sample(1:(1E7*0.5), size=10000)), ncol=2, byrow=TRUE)
test[unlist(apply(Index, 1, function(x){x[1]:x[2]})),] <- 1
于 2013-06-18T21:10:13.750 回答
0

使用对上一个问题的答案来创建行索引向量ridx,然后

res[as.logical(ridx),] = 1L
于 2013-06-18T21:56:43.670 回答