-1

我有以下数据框,

id, date, state
1   2012-01-01 a
1   2012-01-02 a
1   2012-01-03 a
1   2012-01-04 b
1   2012-01-05 b
2   2013-01-01 a
2   2013-01-02 a
2   2013-01-03 b
2   2013-01-04 b

对于每个 id,我想找到状态从 a 变为 b 的日期,然后我希望它作为该 id 的列插入。所以上面的例子会产生

id, date, state, changedate
1   2012-01-01 a 2012-01-03
1   2012-01-02 a 2012-01-03
1   2012-01-03 a 2012-01-03
1   2012-01-04 b 2012-01-03
1   2012-01-05 b 2012-01-03
2   2013-01-01 a 2013-01-02
2   2013-01-02 a 2013-01-02
2   2013-01-03 b 2013-01-02
2   2013-01-04 b 2013-01-02

有没有办法通过 plyr 函数甚至在基础 R 中优雅地做到这一点?提前致谢。

4

1 回答 1

2

编辑:正如塞巴斯蒂安提到的,我假设 data.frame 是按 column 排序的date

众多解决方案之一。可能棘手的一点是找到过渡期。这可以在 的帮助下完成rle

rle.df <- rle(df$state)
# get indices of a-to-b transition -> 3,7
idx <- cumsum(rle.df$lengths)[c(TRUE, FALSE)]
# get indices of b-to-a transition -> 5,9
idx2 <- cumsum(rle.df$lengths)[c(FALSE, TRUE)]
# construct appropriate lengths -> 5,4
idx2 <- c(idx2[1], diff(idx2))
# do a rep with idx2 fro times and df$date[idx] for value
df$changedate <- unlist(lapply(1:length(idx2), function(vv) {
    rep(df$date[idx[vv]], idx2[vv])
}))

> df
  id.      date. state changedate
1   1 2012-01-01     a 2012-01-03
2   1 2012-01-02     a 2012-01-03
3   1 2012-01-03     a 2012-01-03
4   1 2012-01-04     b 2012-01-03
5   1 2012-01-05     b 2012-01-03
6   2 2013-01-01     a 2013-01-02
7   2 2013-01-02     a 2013-01-02
8   2 2013-01-03     b 2013-01-02
9   2 2013-01-04     b 2013-01-02

使用替代解决方案data.table(我刚刚注意到您还有一个.id.列,我们可以使用它拆分并应用通过找到的转换索引的日期rle)。

require(data.table)
rle.df <- rle(df$state)
idx  <- cumsum(rle.df$lengths)[c(TRUE, FALSE)]
idx2 <- cumsum(rle.df$lengths)[c(FALSE, TRUE)]
idx  <- c(idx[1], tail(idx, -1) - head(idx2, -1))

dt <- data.table(df, key="id.")
out <- dt[, `:=`(changedate=date.[idx[id.]]), by=id.]

> out
    id.      date. state changedate
 1:   1 2012-01-01     a 2012-01-03
 2:   1 2012-01-02     a 2012-01-03
 3:   1 2012-01-03     a 2012-01-03
 4:   1 2012-01-04     b 2012-01-03
 5:   1 2012-01-05     b 2012-01-03
 6:   2 2013-01-01     a 2013-01-02
 7:   2 2013-01-02     a 2013-01-02
 8:   2 2013-01-03     b 2013-01-02
 9:   2 2013-01-04     b 2013-01-02
于 2013-01-17T23:21:09.670 回答