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)]
}))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…