如何在R中向量化此for循环

时间:2018-06-29 03:07:07

标签: r loops for-loop vectorization

我在R方面没有太多经验。我有一个这样的for循环:

combination<-read.csv(choose.files())
rownames(n_weight)<-1:154
colnames(n_weight)<-rownames(n_weight)
for(i in 1:length(n_weight)){
  for(j in 1:length(n_weight)){
  if(i==j){
    n_weight[i,j]<-1
  }
}}

idex <- dim(combination)[1]   #idex is length 
m <- as.data.frame(matrix(0, ncol = idex, nrow = idex))
rownames(m) <- as.numeric(combination$FID)
colnames(m) <- rownames(m)



# n_weight: 154X154 matrix
# m: 23562*23562 matrix
# combination: data.frame with 23562 obs. 

for(i in 1:23562){
  for (j in 1:23562){
    if(n_weight[combination[i,]$PC,combination[j,]$PC]==1){
      if(n_weight[combination[i,]$RC,combination[j,]$RC]==1){
        m[i,j]<-1}
    }}}

这花费了太多时间。有没有办法向量化这个循环? 谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下:

<div class="row">
  <div class="wrapper">
    <img src="conselhoantoniobrennand.png">
    <div class="overlay">
      <div class="content">
        <h2> Antônio Brenannd </h2>
        <a id="modalBtn1" class="button"> Saiba mais </a>
      </div>
    </div>
  </div>

  <div id="modalBtn1Target" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="closeBtnbrennand"> &times; </span>
        <h1 style="color: #ffffff; margin: 0;"> Antônio Brennand </h1>
      </div>
      <div class="modal-body">
        <p> <span class="nome"> Antônio Brennand </span> é sócio da Brennand Energia. </p>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="wrapper">
    <img src="conselhoantoniobrennand.png">
    <div class="overlay">
      <div class="content">
        <h2> Antônio Brenannd </h2>
        <a id="modalBtn2" class="button"> Saiba mais </a>
      </div>
    </div>
  </div>

  <div id="modalBtn2Target" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="closeBtnbrennand"> &times; </span>
        <h1 style="color: #ffffff; margin: 0;"> Antônio Brennand </h1>
      </div>
      <div class="modal-body">
        <p> <span class="nome"> Antônio Brennand </span> é sócio da Brennand Energia. </p>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="wrapper">
    <img src="conselhoantoniobrennand.png">
    <div class="overlay">
      <div class="content">
        <h2> Antônio Brenannd </h2>
        <a id="modalBtn3" class="button"> Saiba mais </a>
      </div>
    </div>
  </div>

  <div id="modalBtn3Target" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="closeBtnbrennand"> &times; </span>
        <h1 style="color: #ffffff; margin: 0;"> Antônio Brennand </h1>
      </div>
      <div class="modal-body">
        <p> <span class="nome"> Antônio Brennand </span> é sócio da Brennand Energia. </p>
      </div>
    </div>
  </div>
</div>