0

(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?

SFKR
  • 13
  • 3
  • 4
    You maximise your chance of getting a useful answer if you provide a minimal reproducible example. [This post](https://stackoverflow.com/help/minimal-reproducible-example) may help. – Limey Aug 25 '22 at 08:33
  • Welcome to SO, SFKR! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`) possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Aug 25 '22 at 12:21

0 Answers0