简体   繁体   中英

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".

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. 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.

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. 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.

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 . May I recommend (disclaimer: I'm the author) you take a look at ktsolve package? 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.

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.

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.

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