Arne - 1 year ago 256
R Question

# R: initial condition error in deSolve-package

I just started working with deSolve. For some reason a simple example code gives me this error message:

Error in checkFunc(Func2, times, y, rho) : The number of
derivatives returned by func() (1) must equal the length of the
initial conditions vector (4)

I use the following example code:

``````library(deSolve)
model <- function (time, y, parms) {
with(as.list(c(y, parms)), {
dY1 <- -k1*y1*y2 + k2*y3
dY2 <- k2 * y3 - k1*y1*y2
dY3 <- -k2*y3-k3*y3+k1*y1*y2
dY4 <- k3*y3
list(dY1,dY2,dY3,dY4)
})
}
yini <- c(y1 = 1,y2=1,y3=0,y4=0)
parms <- c(k1=0.1,k2=0.1,k3=0.1)
times <- seq(0, 100, 1)
out <- ode(y=yini, times=times, func=model, parms=parms)
plot(out)
``````

As you can see I have exactly 4 derivatives and 4 initial conditions defined in yini. Therefore, I cannot interpret this error.

How can I solve this problem?

In your function `model` the last line has to be:

``````list(c(dY1,dY2,dY3,dY4))
``````

So the output has to be concatenated `c()` in a vector. This is required by the `deSolve`package.

So the whole function looks like this:

``````model <- function (time, y, parms) {
with(as.list(c(y, parms)), {
dY1 <- -k1*y1*y2 + k2*y3
dY2 <- k2 * y3 - k1*y1*y2
dY3 <- -k2*y3-k3*y3+k1*y1*y2
dY4 <- k3*y3
list(c(dY1,dY2,dY3,dY4))
})
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download