vendredi 17 juillet 2020

Mutate date based on if else condition

I have monthly data, that contains either positive or negative demand. Negative demand normaly occurs in the same or following month when sth. is returned. I want to correct those returns in the following months by subtracting 1 month from the date. For example customer 1 buys 400 units in march, but returns 300 units in april, then I do not want to see thouse outliers but I want to see 100 units for march and zero for april.

I tried the following to create a new column for the correct date: If the flow is negative in one month, then subtract 1 month from the original date, else return the original date.

Just to make sure that it works, I tried the following and this is fine, so I wanted to put this into an ifelse statement

dummy2 <- dummy %>% 
  filter(flows_new <0) %>% 
   mutate(datenew2 = datenew - months(1) )

But all those options throw errors:


    #---option 1
    for (i in 1:length(dummy$flows_new)) {
      if (dummmy$flows_new < 0) {
        dummy$datenew - months(1) 
      }
      else {
       datenew
      }
    }
    #Error: unexpected '=' in:
    "  if (dummmy$flows_new < 0) {
        mutate(dummy$datenew2 ="
     
    #---option2. for if else
    for (i in 1:length(dummy$flows_new)) {
      if (dummmy$flows_new < 0) {
        dummy$datenew - months(1) 
      }
      else {
       dummy$datenew
      }
    }
    #Error in dummmy : object 'dummmy' not found
    
    #---option 3
        dummy$newcol <- 
          ifelse(dummy$flows_new < 0,
                mutate(datenew2 = datenew - months(1)) ,
                datenew)
    
    #Error in mutate(datenew2 = datenew - months(1)) : 
      object 'datenew' not found
    
    #---option 4
    dummy$datenew3 <- dummy %>% 
      ifelse(flows_new < 0,
             datenew2,
             datenew)
    
    #Error in ifelse(., flows_new < 0, datenew2, datenew) : 
      unused argument (datenew)

Aucun commentaire:

Enregistrer un commentaire