mardi 8 janvier 2019

calculate elapsed time based on condition using if () function

I'm trying to calculate the elapsed time based on a certain condition. In the dataset, aDUR to present time elapsed, TSFD represent time in hour. I only need to calculate aDUR when FLAG1 =1, which should be the TSFD of [i+1] record subtract the TSFD of [i] record. When FLAG1 = 0, all records aDUR are assigned with 1.

Here is sample of my dataset.

head(df1_2) C ID DV DATE TIME TSFD TSLD DOSE MDV EVID RATE DUR WT AGE HEIGHT BMI SEX AMT FLAG1 1 NA 11003 . 3/14/2007 22:00 0 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 0 2 NA 11003 . 3/14/2007 23:00 1 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 1 3 NA 11003 . 3/15/2007 1:00 3 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 0 4 NA 11003 . 3/15/2007 2:00 4 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 0 5 NA 11003 . 3/15/2007 3:00 5 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 0 6 NA 11003 . 3/15/2007 4:00 6 0 75 1 1 246. . 54.7 44.6 73 15.89851181 Female 245.97 1

I'm a newbie in R. Here is what I could think of, but it doesn't work. Can someone point out where I did wrong? I also tried ifelse, but I don't know how to calculate the elapsed time within ifelse function.

f2 <-function(fc){
  TSFD <- fc$TSFD
  FLAG1 <- fc$FLAG1
  aDUR <- rep(1,length(FLAG1))
  for (i in 1:length(FLAG1))
   if(FLAG1 == 1) {aDUR[i] <- TSFD[i+1]-TSFD[i]}
  fc$aDUR <- aDUR
  return(fc)
}

Also, I have multiple subjects in the dataset. How could I apply this function based on group of ID? I tried df2 <- df1_2%>%group_by(ID)%>%f2(.). It doesnt work.

Thanks in advance for any input.

Aucun commentaire:

Enregistrer un commentaire