简体   繁体   English

R中的循环内的ODE

[英]ODE inside a loop in R

I'm new to programming and specially R. I find sometimes things easier to get yet more complex to give than Matlab. 我是编程的新手,特别是R。我发现有时候做起来比Matlab更容易,但是却变得更复杂。 I'm trying to recreate a loop that I already have in a "script.m" but I haven't been able to get anything on R. Could anybody please explain me how to run the following for three times this?... 我正在尝试重新创建“ script.m”中已经存在的循环,但是我无法在R上获取任何内容。有人可以向我解释一下如何运行以下命令三遍吗?

Thanks in advance for any help provided 预先感谢您提供的任何帮助

pars  <- c(...)

times <- seq(ti, tf, delta)

state <- c(S = 50, X = 20, P = 0.5)   

SOLVE <- function(pars) { 

    derivs <- function(time, state, pars) {

        with(as.list(c(state, pars)), {
         .
         .
         .
            return(list(c(St, Xt, Pt)))

        })

    }

    return(as.data.frame(ode(y = state, times = times, func = derivs, parms = pars)))  
}


for(i in seq(ti, tf-span, span)) {

     times <- seq(i, i+span, delta)  

     out   <- SOLVE(pars) 

     state <- c(state[1], tail(out[3], 1), tail(out[4], 1))

 }

The error i get is: 我得到的错误是:

Error in checkInput(y, times, func, rtol, atol, jacfunc, tcrit, hmin, : `y' must be numeric checkInput(y,times,func,rtol,atol,jacfunc,tcrit,hmin,:`y'必须为数字错误

Too long for a comment. 评论太久了。 Try: 尝试:

state <- c(state[1], tail(out[[3]], 1), tail(out[[4]], 1))

The way you have it set up, out is a data.frame. 你有它设置的方式, out是一个data.frame。 out[3] returns a data.frame with one column. out[3]返回带有一列的data.frame。 tail(out[3],1) returns a data.frame with one row and one column (but still a data.frame). tail(out[3],1)返回具有一行和一列的data.frame(但仍然是data.frame)。 When you combine these using, eg, 当您将这些结合使用时,例如,

c(state[1],tail(out[3],1),...)

you generate a list , not a numeric, which is causing the error. 您生成列表 ,而不是数字,这会导致错误。

If you reference, eg, out[[3]] you return a vector which elements are the third column of out . 如果引用,例如out[[3]] ,则返回一个向量向量out的第三列。 This is because, in R, a data.frame is by definition a list of vectors, so out[[3]] returns the third element (vector) in that list. 这是因为在R中,data.frame从定义上来说是一个向量列表,因此out[[3]]返回该列表中的第三个元素(向量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM