Calculate elapsed “times”, where the reference time depends on a factor

末鹿安然 提交于 2019-12-02 12:19:51

The 'ave' function is the first thing you should think of when the results is to be a vector with the same length as the number of rows in the dataframe:

 df$elapsed <- ave(df$time, df$id, FUN=function(x) x -min(x) )
 df
  id time elapsed
1  a    1       0
2  a    2       1
3  a    3       2
4  b    4       0
5  b    5       1

Here is a ddply solution

ddply(df, .(id), summarize, time = time, elapsed = seq(length(id))-1)

and one using rle instead

df$elapsed <- unlist(sapply(rle(as.numeric(df$id))$lengths, seq))-1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!