mardi 6 février 2018

Compare each row of a matrix with the rest of the rows

I wanted to ask if there is an efficient way of comparing each row of a matrix with the rest of the rows. Currently I am running the code below but it is taking days to complete. To give more detail:

Each line represents an order.

The first "if" checks skips the comparison if it is the same line (data[i,1] != data[j,1]) and checks that they are from the same customer - i.e. have the same customer id (data[i,5] == data[j,5])

The second "if" checks whether the second line(order) is 3 days after the first.

The code I use is:

n<-nrow(data) d<-character(n)

for (i in 1 :n ){

  for (j in 1 : n)  {             


    if ( data[i,1] != data[j,1]  & data[i,5] == data[j,5] ){

       if(as.numeric(as.Date(data[i,2])-as.Date(data[j,2])) <= 3 &  as.numeric(as.Date(data[i,2])-as.Date(data[j,2])) >= 0 )

          d[i]<-as.character(data[i,1])
    } 
  }  
}

Any help is much appreciated!

Aucun commentaire:

Enregistrer un commentaire