vendredi 25 août 2017

Ifelse statement with dataframe subset using date

I am trying to create a function to apply to a variable in a dataframe that, for a windows of 2 days forward from the current observation, change the value of VarD if in that date window it always take the value 1.

The dataframe looks like this:

VarA     VarB     Date         Diff   VarD
 1         1      2007-04-09    NA     0
 1         1      2007-04-10    0      0
 1         1      2007-04-11   -2      1 
 1         1      2007-04-12    0      1  
 1         1      2007-04-13    2      0  
 1         1      2007-04-14    0      0  
 1         1      2007-04-15   -2      1  
 1         1      2007-04-16    1      0  
 1         1      2007-04-17   -4      1  
 1         1      2007-04-18    0      1  
 1         1      2007-04-19    0      1  
 1         1      2007-04-20    0      1  

The new dataframe should look like the following:

VarA     VarB     Date         Diff   VarD  VarC
 1         1      2007-04-09    NA     0      0
 1         1      2007-04-10    0      0      0
 1         1      2007-04-11   -2      1      1 
 1         1      2007-04-12    0      1      1  
 1         1      2007-04-13    2      0      0  
 1         1      2007-04-14    0      0      0  
 1         1      2007-04-15   -2      1      1  
 1         1      2007-04-16    1      0      0  
 1         1      2007-04-17   -4      1      0  
 1         1      2007-04-18    0      1      0  
 1         1      2007-04-19    0      1      0  
 1         1      2007-04-20    0      1      0  

I have tried the following code:

db$VarC <- 0

for (i in unique(db$VarA)) {
 for (j in unique(db$VarB)) {
  for (n in 1 : lenght(db$Date)) {
   if (db$VarD[n] == 0) {db$VarC[n] <- 0}
    else { db$VarC[n] <- ifelse(0 %in% db[(db$Date >=n & db$Date < n+3,]$VarC, 1,0}
}
}

But I obtain just zeroes in VarC. I have checked the code without the else and it works fine. No error by r if the complete code is run. I do not have any clue on where the problem could be.

Aucun commentaire:

Enregistrer un commentaire