I have a dataset as given by the following code. I am looking for the difference between the row with lowest value before it rises and the subsequent values for each ID after arranging them by time.
df <- data.frame(ID = c(1,1,1,1,1,2,2,2,3,3,3,3,3,3), time=c(6,12,18,24,30,3,9,21,6,12,18,24,30,36), value = c(0.9,0.7,2.8,3.8,0.5,1.3,3.1,0.8,1.2,0.6,3.7,1.8,0.9,0.3))
So for ID 1, I would like to find the difference between 0.7 and subsequent rows. The overall data that I want is this
df1 <- df%>%mutate(value.diff = c(NA, 0, 2.1, 3.1, -0.2, 0, 1.8, 0.5, NA, 0, 3.1, 1.2, 0.3, -0.3))
I applied the following code
df <- df[order(df$ID,df$time),]
df <- df%>%group_by(ID)%>%mutate(value.diff = diff(value-min(value)))
But it is not serving the purpose. I would appreciate any help in this regard.