0

I have a dataframe like this:

day         device      problem
2021-01-01  A           0
2021-01-02  A           1
2021-01-03  A           1
2021-01-04  A           0
2021-01-05  A           0
2021-01-06  A           1
2021-01-07  A           1
2021-01-08  A           1
2021-01-09  A           0
2021-01-10  A           1
2021-01-01  B           1
2021-01-02  B           1
2021-01-03  B           1
2021-01-04  B           1
2021-01-05  B           0
2021-01-06  B           0
2021-01-07  B           1
2021-01-08  B           0
2021-01-09  B           1
2021-01-10  B           0

I would like to know whether there is an efficient way of finding out how many 7 days (rows) windows for any of the devices had at least 1 problem=1 reading?

The expected result would look like this:

day         device      problem    problem_count
2021-01-01  A           0          NA
2021-01-02  A           1          NA
2021-01-03  A           1          NA
2021-01-04  A           0          NA 
2021-01-05  A           0          NA
2021-01-06  A           1          NA
2021-01-07  A           1          4
2021-01-08  A           1          5
2021-01-09  A           0          4
2021-01-10  A           1          4
2021-01-01  B           1          NA
2021-01-02  B           1          NA
2021-01-03  B           1          NA
2021-01-04  B           1          NA
2021-01-05  B           0          NA
2021-01-06  B           0          NA
2021-01-07  B           1          5
2021-01-08  B           0          4
2021-01-09  B           1          4
2021-01-10  B           0          3

Would something like this be possible? Thank you for any suggestions!

dloudtrain
  • 301
  • 2
  • 9
  • Can try ``zoo::rollapply``, e.g., ``data.frame(1:100, 1:100) %>% rollapply(.,7,sum)`` – runr Oct 29 '21 at 06:54
  • 1
    Does this answer your question? [Rolling Sum by Another Variable in R](https://stackoverflow.com/questions/24397299/rolling-sum-by-another-variable-in-r) – caldwellst Oct 29 '21 at 06:54
  • `df %>% group_by(device) %>% mutate(problem_count = zoo::rollsumr(problem == 1, 7, fill = NA))` – Ronak Shah Oct 29 '21 at 06:56

0 Answers0