Reputation: 8494
I have a dataframe
named cin
with repeated measures at different times.
Here is the head(cin)
:
rat t0 t30 t60 t90 t120 t180 t240
1 2 368.140 601.379 683.489 487.085 423.255 306.132 253.108
2 2 35.000 27.000 20.000 12.000 9.000 7.000 7.000
3 2 633.048 546.406 449.268 383.821 358.186 342.300 336.481
4 3 1044.160 738.000 442.000 297.000 234.000 232.000 235.000
5 3 74.000 78.000 67.000 54.000 46.000 41.000 40.000
6 3 211.181 142.615 160.104 163.867 181.148 170.053 189.865
I want to use the calculate the area under the curve, with a formula I saw on this SO post.
Here is my attempt :
times = c(0,30,60,90,120,180,240)
y = as.vector(t(cin[,2:8][1,])) #transposal of the first line -_-
auc_of_first_line = sum(diff(times[order(times)])*rollmean(y[order(times)],2))
This works for the first line (but with the ugly transposal), but I cant seem to find out how to generalize to cin$auc = sum...
How can I do so ?
Upvotes: 0
Views: 56
Reputation: 3369
There are probably more efficient ways of doing this. But this might get you what you're looking for.
times = c(0,30,60,90,120,180,240)
# Transpose cin dataframe
cin <- as.data.frame(t(cin[,2:8]))
# Apply the calculation to each column and bind results to bottom of dataframe
cin <- rbind(cin, apply(cin, 2, function(x) sum(diff(times[order(times)])*rollmean(x,2))))
# Set rowname for calculation to "AUC"
row.names(cin)[length(row.names(cin))] <- "AUC"
# Transpose cin dataframe back to original format
cin <- as.data.frame(t(cin))
Upvotes: 1