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

后端 未结 2 1679
栀梦
栀梦 2021-01-26 14:27

I\'m trying to calculate elapsed times in a data frame, where the \'start\' value for the elapsed time depends on the value of a factor column in the data frame. (To simply the

2条回答
  •  日久生厌
    2021-01-26 15:09

    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
    

提交回复
热议问题