[英]Solving system of nonlinear equations in R
I am trying to solve a system of non-linear equations in R but it keeps giving me this error "number of items to replace is not a multiple of replacement length". 我试图解决R中的非线性方程组,但它一直给我这个错误“要替换的项目数不是替换长度的倍数”。
My code looks like this: 我的代码看起来像这样:
my_data <- Danske
D <- my_data$D
V <- my_data$V
r <- my_data$r
s <- my_data$s
fnewton <- function(x)
{
y <- numeric(2)
d1 <- (log(x[1]/D)+(r+x[2]^2/2))/x[2]
d2 <- d1-x[2]
y[1] <- V - (x[1]*pnorm(d1) - exp(-r)*D*pnorm(d2))
y[2] <- s*V - pnorm(d1)*x[2]*x[1]
y
}
xstart <- c(239241500000, 0.012396)
nleqslv(xstart, fnewton, method="Newton")
D, V, r and s are numeric[1:2508] values and I think thats where the problem comes from. D,V,r和s是数值[1:2508]值,我认为这就是问题所在。 If I have single values 1x1, it solves it well, however, if I insert vectors with 2508 values, it only calculates the first x1 and x2 and then comes the warnings with the message I wrote above.
如果我有单个值1x1,它可以很好地解决它,但是,如果我插入2508个值的向量,它只计算第一个x1和x2,然后出现上面写的消息警告。
Thank you for any help. 感谢您的任何帮助。
Lina 丽娜
Too long for a comment. 评论太久了。
Without having a coy of your data, it's impossible to verify this, but... 没有你的数据腼腆,这是不可能验证这一点,但......
You are passing fnewton(...)
a vector of length 2, and expecting a vector of length 2 as the return value. 你传递
fnewton(...)
一个长度为2的向量,并期望一个长度为2的向量作为返回值。 But in your function, d1
and d2
are set to vectors of length 2508. Then you attempt to set y[1]
and y[2]
to vectors of length 2508. R can't do that, so it uses the first value in the RHS and provides the warnings. 但是在你的函数中,
d1
和d2
被设置为长度为2508的向量。然后你试图将y[1]
和y[2]
设置为长度为2508的向量.R不能这样做,所以它使用了第一个值RHS并提供警告。
I suggest you step through your function and see what each line is doing. 我建议你逐步完成你的功能,看看每条线路在做什么。
Can't propose a solution because I have no idea what you are trying to accomplish. 无法提出解决方案,因为我不知道你想要完成什么。
You don't really have a "system" of equations the way you've written your fnewton
. 你没有像编写
fnewton
那样拥有方程式的“系统”。 May I recommend (disclaimer: I'm the author) you take a look at ktsolve
package? 我可以推荐(免责声明:我是作者)你看看
ktsolve
包吗? You may find that it'll get you the solutions you're looking for a bit more easily. 您可能会发现它可以让您更轻松地找到您正在寻找的解决方案。 You can use your
fnewton
almost as written, except that you will pass a collection of named scalar variables into the function. 您可以使用几乎所写的
fnewton
,除了您将命名标量变量的集合传递给函数。
If you want to solve (either with nleqslv or ktsolve) for a variety of input 'starting points', then you should wrap your approach inside a loop or *apply
function. 如果你想为各种输入“起始点”解决(使用nleqslv或ktsolve),那么你应该将你的方法包装在循环或
*apply
函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.