Akis
Akis

Reputation: 130

how to use apply instead of a loop in R

I am trying to write an algorithm which is very computationally intensive and hence I want to replace every loop with an apply function. However I am pretty stack in the following loop and I am wondering if anyone has any ideas. bc is a matrix of 0s and 1s and ac is a matrix of zeros with the same dim as bc.

for (i in 1:nr){                               
  for (j in 1:nr){
    ac[i,j] <- (bc[i,j]+bc[j,i])/2          
  }
}

Upvotes: 0

Views: 335

Answers (1)

akrun
akrun

Reputation: 886938

We can get the sum of bc and transpose of bc and divide by 2.

(bc+t(bc))/2

Or

Reduce(`+`, list(bc, t(bc)))/2

data

bc <- matrix(1:25, 5,5)
nr <- 5
ac <- matrix(,5,5)

Upvotes: 3

Related Questions