仅对矩阵的某些元素运行(向量化)函数

时间:2016-08-06 01:13:39

标签: r performance

我希望将applyapply的任何变体运行到一个非常大的矩阵(317 x 317)。但我不需要在每个元素上运行此函数,只需要满足特定条件的元素。我还需要相对快速有效地完成这项工作,因为我正在进行大量的模拟。

考虑以下6 x 6示例:

> age
       [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
[1,]    102  20354 194756  75017  68475 193083
[2,]   2274  55366  99150 484081 313875 663767
[3,] 550372 335185 630170  34097 140279 453137
[4,] 275252 219612 332521 109914 263070 235245
[5,] 134672 321061 209240 315383 221653 493812
[6,] 441144 356907 450028 539093 683890 149454

> agedeath
       [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
[1,] 867240 683280 770880 630720 823440 604440
[2,] 543120 166440 674520 876000 876000 604440
[3,] 867240 411720 692040 762120 876000 858480
[4,] 823440 823440 867240 876000 876000 814680
[5,] 849720 849720 586920 508080 481800 876000
[6,] 814680 534360 508080 876000 586920 876000

对我来说重要的元素是age > agedeath,即代码

> which(age > agedeath, arr.ind = T)
     row col
[1,]   6   5
[2,]   2   6

我目前的方法是

  ## check if they will die
  whodies <- which(age > agedeath, arr.ind = T)
  if(nrow(whodies) > 0){
    for(i in 1:nrow(whodies)){
      #whodies[i, 1] is the row, #whodies[i, 2] is the column
      switch_person(stateval, whodies[i, 1], whodies[i, 2])
    }
  }

我希望找到一个不同的,可能是矢量化的解决方案

需要在元素switch_person上运行的函数包含3个参数。

switch_person <- function(switchvalue, i, j){

  ## here we only set a swap. 
  ## the update function will take into account everything else like immunity

  #only run if swap hasnt been set before
  if(swap[i, j]==0){
    deref(swapref)[i,j] = switchvalue
    return(1) #return success
  }
  return(0) #return fail

}

swap是另一个矩阵。所以你可以认为我有一个ageagedeathswap矩阵。如果age > agedeath(对于i,j坐标),我想设置swap[i, j] = some_value

我正在使用ref包,这样我就不会制作很多我的矩阵副本,并且可以修改原始矩阵。

0 个答案:

没有答案
相关问题