title: fast computation of Tomek link in R
body: <p>i want to implement tomek's link for dealing with unbalanced data.
  This code is used for binary classification problem, where the 1 class is the majority class and the 0 class is the minority. X the imput, Y the output
  I've written the following code but i'm looking for a way to speed up computation.</p>
  
  <p>How can i improve my code?</p>
  
  <pre><code>#########################
  #remove overlapping observation using tomek links
  #given observations i and j belonging to different classes
  #(i,j) is a Tomek link if there is NO example z, such that d(i, z) &lt; d(i, j) or d(j , z) &lt; d(i, j)
  #find tomek links and remove only the observations of the tomek links belonging to majority class (0 class).
  #########################
  tomekLink&lt;-function(X,Y,distType="euclidean"){
  i.1&lt;-which(Y==1)
  i.0&lt;-which(Y==0)
  X.1&lt;-X[i.1,]
  X.0&lt;-X[i.0,]
  i.tomekLink=NULL
  j.tomekLink=NULL
  #i and j belong to different classes
  timeTomek&lt;-system.time({
  for(i in i.1){
      for(j in i.0){
          d&lt;-dst(X,i,j,distType)
          obsleft&lt;-setdiff(1:nrow(X),c(i,j))
          for(z in obsleft){
              if ( dst(X,i,z,distType)&lt;d | dst(X,j,z,distType)&lt;d ){
                  break() #(i,j) is not a Tomek link, get next pair (i,j)
                  } 
              #if z is the last obs and d(i, z) &gt; d(i, j) and d(j , z) &gt; d(i, j),then (i,j) is a Tomek link
              if(z==obsleft[length(obsleft)]){
                  if ( dst(X,i,z,distType)&gt;d &amp; dst(X,j,z,distType)&gt;d ){
                      #(i,j) is a Tomek link
                      #cat("\n tomeklink obs",i,"and",j)
                      i.tomekLink=c(i.tomekLink,i)
                      j.tomekLink=c(j.tomekLink,j)
                      #since we want to eliminate only majority class observations
                      #remove j from i.0 to speed up the loop
                      i.0&lt;-setdiff(i.0,j)
                      }
                  }
              }
          }
      }
  })  
  print(paste("Time to find tomek links:",round(timeTomek[3],digit=2))) 
  #id2keep&lt;-setdiff(1:nrow(X),c(i.tomekLink,j.tomekLink))
  id2keep&lt;-setdiff(1:nrow(X),j.tomekLink)
  cat("numb of obs removed usign tomeklink",nrow(X)-length(id2keep),"\n",
      (nrow(X)-length(id2keep))/nrow(X)*100,"% of training ;",
      (length(j.tomekLink))/length(which(Y==0))*100,"% of 0 class")
  X&lt;-X[id2keep,]
  Y&lt;-Y[id2keep]
  cat("\n prop of 1 afer TomekLink:",(length(which(Y==1))/length(Y))*100,"% \n")
  return(list(X=X,Y=Y))
  }
  
  
  #distance measure used in tomekLink function
  dst&lt;-function(X,i,j,distType="euclidean"){
  d&lt;-dist(rbind(X[i,],X[j,]), method= distType)
  return(d)
  }
  </code></pre>