I am looking for help in turning my code into a ‘loop’. I have code that can calculate iAUC for my x (time) and y (one participant). I have almost 40+ participants (all in separate columns) and am hoping to get some help turning this into a loop so I don’t have to do this individually for each participant column! Thanks in advance! This is my data:
[Picture for formatting][1]
t<- 0, 30, 37.5,45,60,90,120,150
P01<- 4.631,4.764,6.784,9.799,7.452,6.673,6.584,7.25
P02<- 5.23,7.965,10.67,12.3,12.53,12.83,11.14,8.478
P04<- 5.84,5.661,7.57,7.615,8.868,8.734,8.6,8.003
[Image of data][2]
I have the following code. It works for one single instance but get errors if I try the ncols function to try to move the ‘v’ argument from participant to participant in each column (keeping the ‘t’ time the same):
t<- data1$Time
v<- data1$`P01-C`
(AUC<-data.frame(t,v))
i_auc.fn <- sapply(TheR_Glucose_SherbrookeHIIT[-1], function(x,y) {
auc <- ifelse(y[2] > y[1], (y[2]-y[1])*(x[2]-x[1])/2, 0)
seg.type <- 0
for (i in 3:length(x)) {
if (y[i] >= y[1] & y[i-1] >= y[1]) {
auc[i-1] <- (((y[i]-y[1])/2) + (y[i-1]-y[1])/2) * (x[i]-x[i-1])
seg.type[i-1] <- 1
} else if (y[i] >= y[1] & y[i-1] < y[1]) {
auc[i-1] <- ((y[i]-y[1])^2/(y[i]-y[i-1])) * (x[i]-x[i-1])/2
seg.type[i-1] <- 2
} else if (y[i] < y[1] & y[i-1] >= y[1]) {
auc[i-1] <- ((y[i-1]-y[1])^2/(y[i-1]-y[i])) * (x[i]-x[i-1])/2
seg.type[i-1] <- 3
} else if (y[i] < y[1] & y[i-1] < y[1]) {
auc[i-1] <- 0
seg.type[i-1] <- 4
break
} else {
return(cat("i:", i, "Error: No condition met\n"))
}
}
return(list(auc=sum(auc), segments=auc, seg.type=seg.type))
}
Compute positive iAUC
iAUC <- i_auc.fn(AUC$t, AUC$v)
iAUC$auc
This returns:
> iAUC$auc
[1] 299.3887
Which works great for P01. But hoping to turn this into a loop!