I would like to calculate reliable improvement or worsening from session 1 to "the last session" in a unbalanced data set organized in long format.
The data i have looks like this:
ID <- c("A","A","B","B","B","C","C","C","C")
Session <-c(1,2,1,2,3,1,2,3,4)
Value <- c(10,6,25,35,15,20,25,35,35)
Have <- data.table(ID,Session,Value)
Have
ID Session Value
A 1 10
A 2 6
B 1 25
B 2 35
B 3 15
C 1 20
C 2 25
C 3 35
C 4 35
The data i need would look like this:
Change <- c(-4,-4,-10,-10,-10,15,15,15,15)
Need <- data.table(ID,Session, Value,Change)
Need
ID Session Value Change
A 1 10 -4
A 2 6 -4
B 1 25 -10
B 2 35 -10
B 3 15 -10
C 1 20 15
C 2 25 15
C 3 35 15
C 4 35 15
I have tried this:
Have$change<-as.vector(unlist(tapply(Have$Value,Have$ID,FUN=function(x){return (x-rep(x[1],length(x)))})));
Have
ID Session Value change
A 1 10 0
A 2 6 -4
B 1 25 0
B 2 35 10
B 3 15 -10
C 1 20 0
C 2 25 5
C 3 35 15
C 4 35 15
I used code from this post Calculating change from baseline with data in long format