Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 209819

Faster matrix multiplication by replacing a double loop

$
0
0

I have a dataframe which looks a bit as produced by the following code (but much larger)

set.seed(10)    
mat <- matrix(rbinom(200, size=1, prob = .5), ncol = 10)

In the columns are issues and 1 indicates that an observation is interested in a specific issue. I want to generate a network comparing all observations and have a count of issues that each dyad is jointly interested in.

I have produced the following code, which seems to be working fine:

mat2 <- matrix(NA,20,20)

for(i in 1:nrow(mat)){
    for(j in 1:nrow(mat)){
       mat2[i,j] <- sum(as.numeric(mat[i,]==1) + as.numeric(mat[j,]==1) == 2)
    }
 }

So I compare every entry with every other entry, and only if both have a 1 entry (i.e., they are interested), then this sums to 2 and will be counted as joint interest in a topic.

My problem is that my dataset is very large, and the loop now runs for hours already.

Does anyone have an idea how to do this while avoiding the loop?


Viewing all articles
Browse latest Browse all 209819

Trending Articles