With a data set:
conc <- data.frame(time = c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration = c(170, 122, 74, 45, 28, 17, 10))
and I would like to fit this data to the differential equation below:
dC/dt= -kC
where C would be the concentration, and time t in the data set. This would also give a result of k. Could anybody give me a clue how to do this in R? Thanks.
First use separation of variables to solve the differential equation. This gives log(C)=-k*t+C0.
Plot the data:
plot(log(concentration) ~ time,data=conc)
Fit a linear model:
fit <- lm(log(concentration) ~ time,data=conc)
summary(fit)
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 5.299355 0.009787 541.4 4.08e-13 ***
# time -0.992208 0.005426 -182.9 9.28e-11 ***
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 0.01388 on 5 degrees of freedom
# Multiple R-squared: 0.9999, Adjusted R-squared: 0.9998
# F-statistic: 3.344e+04 on 1 and 5 DF, p-value: 9.281e-11
Plot the predicted values:
lines(predict(fit)~conc$time)
Extract k:
k <- -coef(fit)[2]
#0.9922081
This could be a solution:
require('deSolve')
conc <- data.frame(time <- c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration <- c(170, 122, 74, 45, 28, 17, 10))
##"Model" with differential equation
model <- function(t, C, k){
list(-k * C)
}
##Cost function with sum of squared residuals:
cost <- function(k){
c.start <- 170
out <- lsoda(c(C=c.start), conc$time, model, k)
c <- sum( (conc$concentration - out[,"C"])^2)
c
}
##Initial value for k
k <- 3
## Use some optimization procedure
opt <- optim(k, cost, method="Brent", lower=0, upper=10)
k.fitted <- opt$par
Maybe it is a bit naive since using lsoda seems to be a bit overkill for calculating with only one differential equation... But it certainly optimizes your k. You might want to check the start value for C for the integration, I set it to 170 here, don't you have a value for t=0?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.