R nls: fitting a curve to data
Asked Answered
H

1

2

I'm having trouble finding the right curve to fit to my data. If someone more knowledgeable than me has an idea/solution for a better fitting curve I would be really grateful.

Data: The aim is to predict x from y

dat <- data.frame(x = c(15,25,50,100,150,200,300,400,500,700,850,1000,1500),
                  y = c(43,45.16,47.41,53.74,59.66,65.19,76.4,86.12,92.97,
                        103.15,106.34,108.21,113) ) 

This is how far I've come:

model <- nls(x ~ a * exp( (log(2) / b ) * y),
             data = dat, start = list(a = 1, b = 15 ), trace = T)

Which is not a great fit:

dat$pred <- predict(model, list(y = dat$y))
plot( dat$y, dat$x, type = 'o', lty = 2)
points( dat$y, dat$pred, type = 'o', col = 'red')

fit plot

Thanks, F

Hadst answered 2/11, 2015 at 13:34 Comment(2)
In plot function in R, first argument is x argument and second argument is y. You have plotted dat$x on y axis. You might want to correct it.Puma
For some things I find Excel more intuitive than R - eg.. you could have fit a trend line in Excel, would have seen that a higher degree polynomial function fits well, and finally u probably would have landed here.Spontoon
D
5

Predicting x from y a 5th degree polynomial is not so parsimonius but does seem to fit:

fm <- lm(x ~ poly(y, 5), dat)
plot(x ~ y, dat)
lines(fitted(fm) ~ y, dat)

(continued after plot)

screenshot

You could also consider the UCRS.5b model of the drc package:

library(drc)
fm <- drm(x ~ y, data = dat, fct = UCRS.5b())
plot(fm)

screenshot

Note: Originally, I assumed you wanted to predict y from x and had written the answer below.

A cubic looks pretty good:

plot(y ~ x, dat)
fm <- lm(y ~ poly(x, 3), dat)
lines(fitted(fm) ~ x, dat)

(continued after plot)

screenshot

A 4 parameter logistic also looks good:

library(drc)
fm <- drm(y ~ x, data = dat, fct = LL.4())
plot(fm)

screenshot

Doordie answered 2/11, 2015 at 13:53 Comment(4)
Thanks ! The cubic looks indeed pretty good. But it predicts y from x, I want to predict x from y.Hadst
Sorry my bad, used the drm instead of the drc packageHadst
P.S I'm not familiar with the drc package. Do you know how to get the predicted x values ? Thanks!Hadst
methods(class = "drc") will show the various methods available for "drc" objects.Doordie

© 2022 - 2024 — McMap. All rights reserved.