Carl Carl - 3 months ago 19
R Question

Recentering an unbalanced time predictor for mixed models

I would like to recenter an unbalanced time predictor in a mixed model so that the intercept reflects end of treatment.

For example:

ID <- c(1,1,2,2,2,3,3,3,3)
Time <- c(0,1,0,1,2,0,1,2,3)
Before <- data.table(ID,Time)
Before

ID Time
1 0
1 1
2 0
2 1
2 2
3 0
3 1
3 2
3 3


I would like to get this:

Recenter <- c(1,0,2,1,0,3,2,1,0)
After <- data.table(ID,Time, Recenter)
After

ID Time Recenter
1 0 1
1 1 0
2 0 2
2 1 1
2 2 0
3 0 3
3 1 2
3 2 1
3 3 0

Answer

Looks like you want to reverse Time within each ID. This is what you need:

Recenter <- unlist(with(Before, tapply(Time, ID, rev)), use.names = FALSE)

by applying rev function to unbalanced / ragged array using tapply.