(Background for this question: I have subject who have switched medical products. During the switch, we need to calculate the remainder of the previous product still left in the body which otherwise will falsely be added to the measured concentration (DV) of the new drug. The upcoming code is to circumvent this problem:)
I have the following question about this line of code --> I named my dataset data and I know how to create a new column "TEST" based on a couple conditions as I show here:
Data$TEST <- 0
Data$TEST[(Data$PROD==4 | Data$PROD==6) & Data$DV>0 & Data$TYPE==1] <- cumsum(1:length(Data$TEST[(Data$PROD==4 | Data$PROD==6) & Data$DV>0 & Data$TYPE==1])).
(next step is:)
Data$TEST2 <- 0
Data$TEST2[Data$TEST == max(Data$TEST)] <- 1
This works fine if there is one subject described in the dataset, however, I have a case where I need to combine multiple subjects into one dataset. Hence, I would like to group for "ID".
My question is thus how to incorporate a group_by(ID) in the first code chunk above. Most preferably I would like to combine the entire first chunk into a pipeline (with %>%) but I am not sure how to do that.
Additional question: How could I handle when there are multiple "max" values per subject? This happens when a subject has switched medications multiple times. In that case the group_by(ID) does not work, as one patient has multiple "max" values. What could be a solution in this case?