mercredi 2 septembre 2020

How to store and use a variable value in a loop?

I am working on a large loop simplified below to highlight the problem. In the dataset "DFloopSub", for each animal I'm studying ("IDTruie") I have several lines.

The aim is to calculate 2 new varaibles ("QuantiteModif" and "Reste") for each line, knowing that "QuantiteModif" (at line "l") needs to take into account the value of "Reste" at previous line (l-1). The loop is not working properly : the column "Reste" is correct, but the column "QuantiteModif" does not take into account the "Reste" ("a" in ifelse statement), instead it only takes the value "0". Can you help me to find why it is not working ?

for(i in unique(DFloopSub[,"IDTruie"])) {        
  
  a <- 6                                         # define the inital value for "Reste" 
  DFloopSub$line <- 1:nrow(DFloopSub)            # include line number
  
  for (l in unique(DFloopSub[,"line"])){         
    

    DFloopSub$QuantiteModif <- ifelse(DFloopSub$JourEntree == DFloopSub$JourSortie,              
                                      DFloopSub$Quantite,
                                      a)    # need to use "Reste" at (l-1)
                                             
    
    DFloopSub$Reste <- ifelse(DFloopSub$JourEntree == DFloopSub$JourSortie,               
                              0,
                              DFloopSub$Quantite - DFloopSub$QuantiteModif)

    a <- DFloopSub$Reste[l]
    #print(a)
  }
} 

Aucun commentaire:

Enregistrer un commentaire