[R] Eliminating For Loop in Comparison and Replacement

Knudson, Anthony Hh (Corvallis-R&D) knudson at hp.com
Thu May 4 23:37:16 CEST 2006


Hi,

I have two dataframes: (Fails, Refurb) each is identical in structure.
The structure has columns consisting of the following: EquipID(Equipment
Identification), CustID(Customer Identification), FailTimes(Time
Equipment Failed).  The for loop below is part of a larger Monte Carlo
simulation involving the reliability of equipment and customers.  


for (i in 1:length(Fails$CustID)){
  j<-1
  while (j <= length(Refurb$CustID)){
    if (Refurb$FailTimes[j] < Fails$FailTimes[i]){
      CustReceiver<-c(CustReceiver,Fails$CustID[i]) 
      PrintDonor<-c(PrintDonor,Refurb$EquipID[j])        
      Refurb<-Refurb[j!=1:length(Refurb$EquipID),]          
      j<-1
    }
  j<-j+1    
  }      
}

What this loop does is compare the Fails dataframe to the Refurb
dataframe and if the fail time of one of the Refurb items is less than
the fail time of the Fails item, the Fails customer gets the Refurb
item.  The CustReceiver tracks which customer receives a Refurb item,
the PrintDonor tracks the Equipment ID that that particular customer
will receive.  Once a Refurb item is given to a customer it is removed
from the Refurb dataframe.  The loop then moves on to the next customer
to see if a Refurb unit exists for them, and resets the Refurb counter
to one.

I've managed to eliminate all other for loops in my simulation except
this one.  What I would like to do is use Rs indexing capability instead
of a for loop to accomplish this.  Any thoughts?

Tony Knudson
Hewlett-Packard
Reliability Knowledge Center
(541)715-8866




More information about the R-help mailing list