I am trying to do a parameter estimation with nls on a function that uses integrate. The function intsol1 involving integrate appears to compute fine on its own for individual values of it arguments.
However, when I try to call it in nls, the integration it does not work.
The error I get is:
Error in integrate(aint1, lower = 0, upper = t) :
length(upper) == 1 is not TRUE
I had the same issue when I tried to do a plot intsol1 with geom_function in ggplot.
Any input on this is appreciated.
library(nls.multstart)
library(aomisc)
diffusion1d <- function(x=1,t,diff=1){
sig <- sqrt(t*diff*2)
df <- dnorm(x,mean=0,sd=sig)
df <- ifelse(t == 0, 0, df)
}
intsol1 <- function(x=1,t,diff=1,cl=1){
x <- x
diff <- diff
cl <- cl
# Integrating factor solution 1-D diffusion with reaction
aint1 <- function(t){exp(cl*t)*diffusion1d(x,t,diff)}
aint1 <- Vectorize(aint1)
bint1 <- exp(-cl*t)*integrate(aint1,lower=0,upper=t)$value
return(bint1)
}
nlsdata <- data.frame(Time_days = c(0.4032258, 1.6129032, 2.0161290, 2.4193548, 3.6290323, 4.8387097, 6.4516129, 10.0806452, 13.7096774, 21.3709677, 28.2258065, 35.0806452, 41.9354839, 56.0483871, 69.7580645, 83.4677419), Concentration_mcg_ml = c(1.5151515, 3.3333333, 4.5454545, 5.2727273, 5.5757576, 5.8181818, 5.5757576, 4.4848485, 3.8787879, 2.6060606, 1.7575758, 1.2727273, 0.9090909, 0.4242424, 0.2424242, 0.1212121))
# x, diff, cl are parameters to be estimated with nls
nlsfit1 <- nls_multstart(Concentration_mcg_ml~ intsol1(x,Time_days,diff,cl), data = nlsdata,
lower=c(x=0, diff=0, cl=0),
upper=c(x=1, diff=1, cl=1),
start_lower = c(x=0, diff=0, cl=0),
start_upper = c(x=1, diff=1, cl=1),
iter = 10,
supp_errors = "N")
nlssummary1 <- summary(nlsfit1)```