如何从天开始获取startdate和enddate(累积)
Variable A days stardate enddate(cumulative)
A 2 0 2
A 3 2 5
B 4 5 9
A 3 0 3
B 8 3 11
答案 0 :(得分:1)
使用cumsum
和shift
的组合:
dt1[, grp := cumsum(shift(Variable, fill='A')=='B')
][, startdate := cumsum(shift(days, fill = 0)), grp
][, enddate := startdate + days][]
给出:
> dt1
Variable days grp startdate enddate
1: A 2 0 0 2
2: A 3 0 2 5
3: B 4 0 5 9
4: A 3 1 0 3
5: B 8 1 3 11
使用过的数据:
dt1 <- data.table(Variable = c("A","A","B","A","B"), days = c(2,3,4,3,8))
答案 1 :(得分:0)
如果我理解正确,您希望days + startdate位于enddate列中。然后你可以简单地使用它:
df <- data.table(Variable=c("A", "A", "B", "A", "B"), days=c(2,3,4,3,8), startdate=c(0,2,5,9,12), enddate=c(0))
df$enddate <- as.numeric(df$days + df$startdate)