This R code is setting up an example of the issue I am attempting to resolve. The data set measures a release of particles over non-uniform time intervals. The particle release is integrated over time using the trapezoid rule.
library(caTools)
test.data.frame <- data.frame(
sample = c('sample 1','sample 1','sample 1','sample 1',
'sample 2','sample 2','sample 2','sample 2'))
test.data.frame$time <- c(1,2,4,6,1,4,5,6)
test.data.frame$material.released.g <- c(5,3,2,1,2,4,5,1)
split.test <- split(test.data.frame, test.data.frame$sample)
integrate.test <- function(x){
dataframe.segment <- do.call(rbind.data.frame,x)
return(trapz(dataframe.segment$time,dataframe.segment$material.released.g))
}
So far the integrate.test function appears to work on a single element of a list.
> integrate.test(split.test[1])
[1] 12
> integrate.test(split.test[2])
[1] 16.5
The lapply function gives zeros in the output.
> lapply(split.test, integrate.test)
$`sample 1`
[1] 0
$`sample 2`
[1] 0
The output I am looking for is a data frame equivalent to:
expected.output <- data.frame(
sample = c('sample 1','sample 2'),
total.material.released = c(12 , 16.5))
Is anyone able to help resolve the error code. Thanks!