I have the following dataframe with 6 columns and several thousand rows.
Example: Screenshot of example data
Each column represents a different timepoint 0,1,3,6,9,12. I want to calculate the area under the curve for each row of values. For example for row 1, I would use the following function from the DescTools package
x=c(0,1,3,6,9,12)
y=c(130, 125, 120, 115, 108, 115)
AUC(x, y, method = c("linear"), na.rm=FALSE)
Is there a way to create a new variable which is the AUC for each row from my dataframe?
Thanks!
CodePudding user response:
We can use apply
with MARGIN = 1
to do rowwise
library(DescTools)
i1 <- rowSums(!is.na(df1)) >2
df1$AUC[i1] <- apply(df1[i1,], 1, FUN = function(y)
AUC(x, y, method = "linear", na.rm = FALSE))
df1$AUC[i1]
[1] 1394 1518
data
df1 <- structure(list(col1 = c(130, 140), col2 = c(125, 137), col3 = c(120,
125), col4 = c(115, 120), col5 = c(108, 125), col6 = c(115, 130
)), class = "data.frame", row.names = c(NA, -2L))
x <- c(0,1,3,6,9,12)