Reputation: 1985
I have a question regarding an algorithm that I don't know how to solve.
I have a dataset that looks like this:
Time Dose ID
0 0 1
0.1 1 1
0.2 0 1
0.3 0 1
0.4 1 1
0.5 0 1
0.7 0 1
0 0 2
0.2 0 2
0.3 1 2
0.4 0 2
0.6 0 2
0.8 1 2
0.9 0 2
1.0 1 2
1.5 0 2
There's many subjects in the dataset, with each subject dosed at different times. What I want to calculate is to calculate a column of data, which is the time after last dose for each subject. Since each subject is dosed several times, how do I update the number of time subtracted from the R program? Thank you!
The expected look would be:
Time Dose ID TPD
0 0 1 0
0.1 1 1 0
0.2 0 1 0.1
0.3 0 1 0.2
0.4 1 1 0
0.5 0 1 0.1
0.7 0 1 0.3
0 0 2 0
0.2 0 2 0.2
0.3 1 2 0
0.4 0 2 0.1
0.6 0 2 0.3
0.8 1 2 0
0.9 0 2 0.1
1.0 1 2 0
1.5 0 2 0.5
Upvotes: 1
Views: 1551
Reputation: 5951
Maybe this is what you are looking for
library(dplyr)
df %>% arrange(ID, Time) %>% group_by(ID) %>%
mutate(TPD=(Time-cummax(Time*Dose))*cummax(Dose)) %>% ungroup
Data
df <- data.frame(Time=c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0, 0.2, 0.3, 0.4, 0.6, 0.8, 0.9, 1.0, 1.5),
Dose=c(0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0),
ID=c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2))
If your data is not sorted then:
library(dplyr)
df %>% arrange(ID, Time) %>% group_by(ID) %>%
mutate(TPD=(Time-cummax(Time*Dose))*cummax(Dose)) %>% ungroup
Upvotes: 1