jeudi 18 septembre 2014

How to write the for-loop into a function. How to apply it by subject ID


Vote count:

0




I have the a dataframe (Table below): I have a code that calculates the values of A1 and A2 and fill them in the dataframe. Here is my code for calculating A1, A2 for a subject.



#Set parameter values needed for calcuation
k10 <- 0.2
k12 <- 0.1
k21 <- 0.04
k20 <- 0
E1 <- k10+k12
E2 <- k21+k20
lambda1 = 0.3145683
lambda2 = 0.02543168

#Matrix calculations
for(i in 2:nrow(df))
{

t <- df$TIME[i]-df$TIME[i-1]
A1last <- df$A1[i-1]
A2last <- df$A2[i-1]
A1term = (((A1last*E2+A2last*k21)-A1last*lambda1)*exp(-t*lambda1)-((A1last*E2+A2last*k21)-A1last*lambda2)*exp(-t*lambda2))/(lambda2-lambda1)
df$A1[i] = A1term + df$AMT[i]

A2term = (((A2last*E1+A1last*k12)-A2last*lambda1)*exp(-t*lambda1)-((A2last*E1+A1last*k12)-A2last*lambda2)*exp(-t*lambda2))/(lambda2-lambda1)
df$A2[i] = A2term

}


I would appreciate if somebody help me in: 1) apply the matrix calculation above for every ID (i.e. calculate for A1, A2 for ID=1, then reset and calculate A1, A2 for ID=2 and fill them in the dataframe) 2) put the matrix calculations in a function.


Here is how my dataframe looks like (Note: the code for creating this df in R is also provide below)



df <- ID TIME AMT A1 A2 DV WT
1 0 100 100 0 NA 70
1 1 0 NA NA NA 70
1 2 0 NA NA NA 70
1 3 0 NA NA NA 70
1 4 0 NA NA NA 70
1 5 0 NA NA NA 70
1 6 100 NA NA NA 70
1 6 0 NA NA NA 70
1 7 0 NA NA NA 70
1 8 0 NA NA NA 70
1 9 0 NA NA NA 70
1 10 0 NA NA NA 70
1 11 0 NA NA NA 70
2 0 50 50 0 NA 120
2 1 0 NA NA NA 120
2 2 0 NA NA NA 120
2 3 0 NA NA NA 120
2 4 0 NA NA NA 120
2 5 0 NA NA NA 120
2 6 0 NA NA NA 120
2 7 50 NA NA NA 120
2 8 0 NA NA NA 120
2 9 0 NA NA NA 120
2 10 0 NA NA NA 120
2 11 0 NA NA NA 120
2 12 0 NA NA NA 120
2 13 0 NA NA NA 120
2 14 0 NA NA NA 120
2 15 0 NA NA NA 120
2 16 0 NA NA NA 120
2 17 0 NA NA NA 120
2 18 0 NA NA NA 120
2 19 0 NA NA NA 120
2 20 0 NA NA NA 120

rm(list=ls(all=TRUE))
dosetimes <- c(0,6,12,18)
df <- data.frame("ID"=1,"TIME"=sort(unique(c(seq(0,30,1),dosetimes))),"AMT"=0,"A1"=NA,"A2"=NA,"DV"=NA,"WT"=NA)
doserows <- subset(df, TIME%in%dosetimes)
doserows$AMT[doserows$TIME==dosetimes[1]] <- 100
doserows$AMT[doserows$TIME==dosetimes[2]] <- 100
doserows$AMT[doserows$TIME==dosetimes[3]] <- 50
doserows$AMT[doserows$TIME==dosetimes[4]] <- 50
df <- rbind(df,doserows)
df <- df[order(df$TIME,-df$AMT),]
df <- subset(df, (TIME==0 & AMT==0)==F)
df$WT <- 70
df$WT[df$TIME >= 12] <- 120
df$ID[(df$WT>=120)==T] <- 2
df$TIME[df$ID==2] <- c(seq(0,20,1))
df$A1[df$TIME==0] <- df$AMT[(df$TIME ==0)]
df$A2[df$TIME==0] <- 0


Thank you in advance !




akrun

10.3k

asked 1 min ago







How to write the for-loop into a function. How to apply it by subject ID

Aucun commentaire:

Enregistrer un commentaire