Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

r - Create groups based on column value with variable rolling window

Good morning,

I'm struggling in the section of a data.table operation.

Reproductible Data

set.seed(5)
df <- data.table(
  id = c(paste0("id", seq(0,9))),
  booleean = c(TRUE, FALSE, rep(TRUE, 3), rep(FALSE,2), rep(TRUE,2),FALSE),
  value = rnorm(10, 14, 5))

     id booleean  value
 1: id0     TRUE    9.79
 2: id1    FALSE   20.92
 3: id2     TRUE    7.72
 4: id3     TRUE   14.35
 5: id4     TRUE   22.55
 6: id5    FALSE   10.98
 7: id6    FALSE   11.63
 8: id7     TRUE   10.82
 9: id8     TRUE   12.57
10: id9    FALSE   14.69

I'm trying to assign a new group value based on a booleean column value. In my code the TRUE/FALSE logic is based on timestamp comparison, the idea is to regroup close events together.

Goal

The rolling window I'm looking to define is [FALSE, all TRUE]. The first individual of a group is always FALSE (except the first row of the datatable), then all other individuals of the group must be TRUE. When I encounter a new FALSE, we create a new group.

Desired Output

     id booleean   value   new_group
 1: id0     TRUE    9.79         1
 2: id1    FALSE   20.92         2
 3: id2     TRUE    7.72         2
 4: id3     TRUE   14.35         2
 5: id4     TRUE   22.55         2
 6: id5    FALSE   10.98         3
 7: id6    FALSE   11.63         4
 8: id7     TRUE   10.82         4
 9: id8     TRUE   12.57         4
10: id9    FALSE   14.69         5
question from:https://stackoverflow.com/questions/65886207/create-groups-based-on-column-value-with-variable-rolling-window

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...