加速大矩阵子集和加法

时间:2014-01-29 17:54:44

标签: r matrix

我正在尝试加速这个子集和添加包含数值和NA值的大型矩阵,目前我的计算机上运行时间不到2秒。我希望加快速度,因为我必须以不同的值运行它数千次。

示例数据:

set.seed(1)
ids = 1:500
row_ids_1 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
row_ids_2 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
row_ids_3 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
row_ids_4 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
row_ids_5 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
row_ids_6 = sample(c(rep(0, 100000), sample(ids, 400000, replace = TRUE)))
matrix_1 = matrix(sample(1:100, length(ids)*20, replace = TRUE), nrow = length(ids), ncol = 20)
matrix_2 = matrix(sample(1:100, length(ids)*20, replace = TRUE), nrow = length(ids), ncol = 20)

表达我希望加快速度:

result <-
  matrix_1[match(row_ids_1, ids),] + 
  matrix_2[match(row_ids_2, ids),] + 
  matrix_2[match(row_ids_3, ids),] + 
  matrix_2[match(row_ids_4, ids),] + 
  matrix_2[match(row_ids_5, ids),] + 
  matrix_2[match(row_ids_6, ids),]

0 个答案:

没有答案