title: How to vectorize this for loop in R
body: <p>I don't have much experience in R. I have a for loop like this:</p>
  
  <pre><code>combination&lt;-read.csv(choose.files())
  rownames(n_weight)&lt;-1:154
  colnames(n_weight)&lt;-rownames(n_weight)
  for(i in 1:length(n_weight)){
    for(j in 1:length(n_weight)){
    if(i==j){
      n_weight[i,j]&lt;-1
    }
  }}
  
  idex &lt;- dim(combination)[1]   #idex is length 
  m &lt;- as.data.frame(matrix(0, ncol = idex, nrow = idex))
  rownames(m) &lt;- as.numeric(combination$FID)
  colnames(m) &lt;- 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]&lt;-1}
      }}}
  </code></pre>
  
  <p>This is taking too much of time. Is there a way to vectorize this loop?
  Thank you!</p>