Avoid the use of loops (for) with R

Posted by albergali on Stack Overflow See other posts from Stack Overflow or by albergali
Published on 2010-06-02T10:37:58Z Indexed on 2010/06/02 12:24 UTC
Read the original article Hit count: 259

Filed under:
|
|
|

Hi,

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

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

where :

  • data is a vector with 100 rows and 1 column
  • paths is a matrix with 100 rows and 5 columns
  • cluster is a matrix with 100 rows and 5 columns

My question is: how could I avoid the use of "for" loops to iterate through the matrix? I don't know whether apply functions (lapply, tapply...) are useful in this case.

This is a problem when j=10000 for example, because execution time is very long.

Thank you

© Stack Overflow or respective owner

Related posts about beginner

Related posts about optimization