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

前端 未结 3 2029
感情败类
感情败类 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:38

    Let's assume that dates are already sorted. I would probably retrieve the first value for each id and then use this to compute the diff feature. Something like this.

    my.df <- data.frame(
      id = c(2380, 2380, 2380, 2380, 20100,20100,20100, 20100, 20103, 20103),
      date = c("10/30/12", "10/31/12", "11/1/12", "11/2/12", "10/30/12", "10/31/12", "11/1/12", "11/2/12", "10/30/12", "10/31/12"),
      value = c(21.01, 22.04, 22.65, 23.11, 35.21, 37.07, 38.17, 38.97, 57.98, 60.83),
      stringsAsFactors = F)
    #
    # get ids
    my.ids <- unique(my.df$id) # or levels(my.df$id)
    
    # get first val (assuming sorting by date)
    id.val0 <- sapply(my.ids, (function(id){
      my.df$value[my.df$id == id][1]
    }))
    names(id.val0) <- my.ids
    
    # do operation
    my.df$diff <- sapply(1:nrow(my.df), (function(i){
      tmp.id <- my.df$id[i]
      my.df$value[i] - id.val0[as.character(tmp.id)]
    }))
    

提交回复
热议问题