0
for(i in length(refunded_customers$buyer_email)) {
  x <- i+1
  if(refunded_customers$buyer_type[i] == "regular" &&
     any(refunded_customers$buyer_email[i] ==
         refunded_customers$buyer_email[
           x:tail(which(
             refunded_customers$transaction_date == 
               (refunded_customers$transaction_date[i] + 90)
           ), n=1)
         ]
       )
    ) {
      refunded_customers[i,10] <- "not churn"
    }

when I use above code I get "refunded_customers$transaction_date[i] + : argument of length 0" error

However when I run the part causing the error outside of the loop (like the one below) it works. Can you identify what the problem is?


any(refunded_customers$buyer_email[12]== refunded_customers$buyer_email[32:(tail(which(refunded_customers$transaction_date==(refunded_customers$transaction_date[12]+30)), n=1))])                                              
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • I think you've got a few issues. I tried to fix spacing and indenting to make things a little more reasonable. `for(i in length(...` looks like a classic mistake where you probably want `for (i in 1:length(...` (or more safely `for(i in seq_along(...`. Your error probably is due to no rows meeting the `refunded_customers$transaction_date == (refunded_customers$transaction_date[i] + 90)` condition.... – Gregor Thomas Mar 07 '22 at 15:19
  • If that is all `FALSE`, then the `which()` of that will be empty, and you're trying to run (picking a sample value of `x = 5`) `5:tail(which(FALSE))`. You can't run a sequence from `x` to `NULL`. – Gregor Thomas Mar 07 '22 at 15:19
  • If you need more help than that, please provide a little bit of sample input reproducibly and confirm what the desired output is. `dput()` is a very nice way to share sample data that is copy/pasteable and includes all class and structure info. `dput(refunded_customers[1:20, c("relevant", "column", "names")])` – Gregor Thomas Mar 07 '22 at 16:22
  • I don't think there is a problem with `which()` because `which(refunded_customers$transaction_date==(refunded_customers$transaction_date[5]+30))` gives 57, 58, 59,60 as a result. thus `tail()` of it would be 60. @GregorThomas I have also tried syntax related comments of yours but they did not work as well. Thanks anyways. Please let me know if there is anything that comes up – Beyza Çokkeçeci Mar 08 '22 at 12:29
  • If you need more help making a reproducible example of your data [see the FAQ here](https://stackoverflow.com/q/5963269/903061). I don't think we can help more without sample data to try the code on. – Gregor Thomas Mar 08 '22 at 14:20

0 Answers0