Avoid the use of for loops

后端 未结 2 1694
迷失自我
迷失自我 2021-02-11 09:28

I\'m working with R and I have a code like this:

for (i in 1:10)
   for (j in 1:100)
        if (data[i] == paths[j,1])
            cluster[i,4] <         


        
相关标签:
2条回答
  • 2021-02-11 10:07

    Inner loop could be vectorized

    cluster[i,4] <- paths[max(which(data[i]==paths[,1])),2]
    

    but check Musa's comment. I think you indented something else.

    Second (outer) loop could be vectorize either, by replicating vectors but

    1. if i is only 100 your speed-up don't be large
    2. it will need more RAM

    [edit] As I understood your comment can you just use logical indexing?

    indx <- data==paths[, 1]
    cluster[indx, 4] <- paths[indx, 2]
    
    0 讨论(0)
  • 2021-02-11 10:13

    I think that both loops can be vectorized using the following:

    cluster[na.omit(match(paths[1:100,1],data[1:10])),4] = paths[!is.na(match(paths[1:100,1],data[1:10])),2]
    
    0 讨论(0)
提交回复
热议问题