简体   繁体   中英

How to calculate the time difference between two event in R?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM