# Function to compute incremental AUC by the method of Brouns et al (2005)¹,
# p.162.
# Inputs:
#     x: vector of values (times) at which observations were taken
#     y: vector of length(x) of observations taken at times x
# Output: A list with the following components:
#     auc:       The (incremental) area under the curve
#     segments:  Vector of length(x-1) of contributions to the AUC 
#                between each of the times in x
#     seg.typte: Vector of length(x-1) indicating what method was 
#                used to calculate each segment.  The initial segment 
#                is assigned 0; for other segments, an integer corresponding
#                to which if-block was used for the calculation
auc.fn <- 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])/2
            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
        } else {
            # The above cases are exhaustive, so this should never happpen
            return(cat("i:", i, "Error: No condition met\n"))
        }
    }
    return(list(auc=sum(auc), segments=auc, seg.type=seg.type))
}

# Data²
time <- c(0,30,45,60,120,180)
potato <- c(89,133,138,125,92,88)
glucose <- c(92,136,132,121,90,82)

# Compute AUC for potato
(auc.potato <- auc.fn(time, potato))
## $auc
## [1] 1980
## 
## $segments
## [1] 660.00 348.75 318.75 585.00  67.50
## 
## $seg.type
## [1] 0 1 1 1 3
# Compute AUC for glucose
(auc.glucose <- auc.fn(time, glucose))
## $auc
## [1] 2047.621
## 
## $segments
## [1] 660.000 315.000 258.750 813.871   0.000
## 
## $seg.type
## [1] 0 1 1 3 4
# Compute glycemic index
auc.potato$auc / auc.glucose$auc * 100
## [1] 96.69758

¹Brouns F, Bjorck I, Frayn KN, et al. Glycaemic index methodology. Nutrition Research Reviews (2005); 18:145-171.

²Crapo PA, Reaven G, Olefsky, J. Postrprandial Plama-glucose and -insulin responses to different complex carbohydrates. Diabetes (1977); 26:1178-83.