Search code examples
rpredictnonlinear-functions

R: Finding solutions for new x values with nlmrt


Good day,

I have tried to figure this out, but I really can't!! I'll supply an example of my data in R:

x <- c(36,71,106,142,175,210,246,288,357)
y <- c(19.6,20.9,19.8,21.2,17.6,23.6,20.4,18.9,17.2)
table <- data.frame(x,y)

library(nlmrt)
curve <- "y~ a + b*exp(-0.01*x) + (c*x)"
ones <- list(a=1, b=1, c=1)

Then I use wrapnls to fit the curve and to find a solution:

solve <- wrapnls(curve, data=table, start=ones, trace=FALSE)

This is all fine and works for me. Then, using the following, I obtain a prediction of y for each of the x values:

predict(solve)

But how do I find the prediction of y for new x values? For instance:

new_x <- c(10, 30, 50, 70)

I have tried:

predict(solve, new_x)
predict(solve, 10)

It just gives the same output as:

predict(solve)

I really hope someone can help! I know if I use the values of 'solve' for parameters a, b, and c and substitute them into the curve formula with the desired x value that I would be able to this, but I'm wondering if there is a simpler option. Also, without plotting the data first.


Solution

  • Predict requires the new data to be a data.frame with column names that match the variable names used in your model (whether your model has one or many variables). All you need to do is use

    predict(solve, data.frame(x=new_x))
    # [1] 18.30066 19.21600 19.88409 20.34973
    

    And that will give you a prediction for just those 4 values. It's somewhat unfortunate that any mistakes in specifying the new data results in the fitted values for the original model being returned. An error message probably would have been more useful, but oh well.