I have the following data.table. For each group of ID&drug I would like to assign a new variable (maxi). Maxi is the highest value of val1 in the group which comes before the highest val2 in the group.
library(data.table)
id <- c(1,1,1,1,2,2,2,3,3,3)
val1 <- c(17,18,19,13,11,12,14,15,20,21)
val2 <- c(20,21,30,32,33,34,36,20,31,28)
drug <- c("A","A","A","B","B","A","A","A","B","B")
dat <- data.table(id,val1,val2,drug)
id val1 val2 drug
1: 1 17 20 A
2: 1 18 21 A
3: 1 19 30 A
4: 1 13 32 B
5: 2 11 33 B
6: 2 12 34 A
7: 2 14 36 A
8: 3 15 20 A
9: 3 20 31 B
10: 3 21 28 B
So for id==2 and drug==A the highest value for val2 is 36 and the highest possible value that comes before 36 in column val1 is 14. The output would look something like this:
id val1 val2 drug maxi
1: 1 17 20 A 19
2: 1 18 21 A 19
3: 1 19 30 A 19
4: 1 13 32 B 13
5: 2 11 33 B 11
6: 2 12 34 A 14
7: 2 14 36 A 14
8: 3 15 20 A 15
9: 3 20 31 B 21
10: 3 21 28 B 21
The final snippet of code I tried is the following:
dat[,maxi := dat[(.I[age < age_check]),age,by = .(id, drug)],by = .(id, drug)]
Thanks!