R subtract value for the same ID (from the first ID that shows)

前端 未结 3 2025
感情败类
感情败类 2020-12-22 04:25

I have a similar question to the question found here: R, subtract value from previous row, group by (slight modification; see below):

In R, lets say I have this da

3条回答
  •  执念已碎
    2020-12-22 04:51

    We can use functions from dplyr. dt is the original data. dt2 is the final output.

    library(dplyr)
    
    dt2 <- dt %>%
      group_by(id) %>%
      mutate(diff = value - first(value))
    
    dt2
    Source: local data frame [10 x 4]
    Groups: id [3]
    
          id       date value  diff
               
    1   2380 10/30/2012 21.01  0.00
    2   2380 10/31/2012 22.04  1.03
    3   2380  11/1/2012 22.65  1.64
    4   2380  11/2/2012 23.11  2.10
    5  20100 10/30/2012 35.21  0.00
    6  20100 10/31/2012 37.07  1.86
    7  20100  11/1/2012 38.17  2.96
    8  20100  11/2/2012 38.97  3.76
    9  20103 10/30/2012 57.98  0.00
    10 20103 10/31/2012 60.83  2.85
    

提交回复
热议问题