Vicki1227
Vicki1227

Reputation: 151

count numbers by group when condition met in R loop

I have a time series data. I would like to group and number rows when column "soak" > 3600. The first row when soak > 3600 is numbered as 1, and the consecutive rows are numbered consequently until another row met the condition of soak > 3600. Then that row and consequent rows are numbered as 1, 2, 3, ...repeat...

I tried to write a loop in R but did not work. I have little background on writing loop in R. But the general idea is something like my code shows. A small sample of my data is also provided.

starts <- structure(list(datetime = structure(c(1440578907, 1440579205, 
1440579832, 1440579885, 1440579926, 1440579977, 1440580044, 1440580106, 
1440580195, 1440580256, 1440580366, 1440580410, 1440580476, 1440580529, 
1440580931, 1440580966, 1440587753, 1440587913, 1440587933, 1440587954
), class = c("POSIXct", "POSIXt"), tzone = ""), soak = c(NA, 
70L, 578L, 21L, 2L, 41L, 14L, 16L, 32L, 9L, 45L, 20L, 51L, 25L, 
364L, 4L, 6764L, 20L, 4L, 5L)), row.names = c(NA, -20L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x000000000a4d1ef0>)




for (j in 0:length(starts)) {
    if(j > startIndex) {
      if(starts[j, soak] >= 3600 && starts[j-1, soak]< 3600) {
        Group2 == 1
      }
    }

    if(starts[j, soak] >= 3600) {
      Group2 <- Group2 + 1
      Group2[j] <- 1
    } else {
      Group2[j] <- Group2
    }
  }


Upvotes: 0

Views: 286

Answers (1)

Shree
Shree

Reputation: 11150

Here's a way using ave from base R -

starts$group <- with(starts, 
                  ave(soak, cumsum(replace(soak, is.na(soak), 0) > 3600), FUN = seq_along)
                )


              datetime soak  group
1  2015-08-26 04:48:27   NA      1
2  2015-08-26 04:53:25   70      2
3  2015-08-26 05:03:52  578      3
4  2015-08-26 05:04:45   21      4
5  2015-08-26 05:05:26    2      5
6  2015-08-26 05:06:17   41      6
7  2015-08-26 05:07:24   14      7
8  2015-08-26 05:08:26   16      8
9  2015-08-26 05:09:55   32      9
10 2015-08-26 05:10:56    9     10
11 2015-08-26 05:12:46   45     11
12 2015-08-26 05:13:30   20     12
13 2015-08-26 05:14:36   51     13
14 2015-08-26 05:15:29   25     14
15 2015-08-26 05:22:11  364     15
16 2015-08-26 05:22:46    4     16
17 2015-08-26 07:15:53 6764      1
18 2015-08-26 07:18:33   20      2
19 2015-08-26 07:18:53    4      3
20 2015-08-26 07:19:14    5      4

Upvotes: 2

Related Questions