简体   繁体   中英

How to fit a curve to data in R and get the equation?

I have a dataframe with x and y values that when plotted, have a shape that looks like that of a shifted lognormal distribution. The data is:

       x      y
400.0000 0.0158
410.3448 0.0373
420.6897 0.0379
431.0345 0.0303
441.3793 0.0250
451.7241 0.0212
462.0690 0.0234
472.4138 0.0295
482.7586 0.0329
493.1034 0.0364
503.4483 0.0469
513.7931 0.0678
524.1379 0.0851
534.4828 0.0693
544.8276 0.0508
555.1724 0.0482
565.5172 0.0617
575.8621 0.2510
586.2069 0.6570
596.5517 0.7360
606.8966 0.6690
617.2414 0.5810
627.5862 0.5060
637.9310 0.4390
648.2759 0.3640
658.6207 0.2980
668.9655 0.2390
679.3103 0.1480
689.6552 0.0496
700.0000 0.0122

and can be recreated in R with:

df = data.frame("x"=c(400.0000, 410.3448, 420.6897, 431.0345, 441.3793, 451.7241, 462.0690, 472.4138, 482.7586, 493.1034, 503.4483, 513.7931, 524.1379, 534.4828, 544.8276, 555.1724, 565.5172, 575.8621, 586.2069, 596.5517, 606.8966, 617.2414, 627.5862, 637.9310, 648.2759, 658.6207, 668.9655, 679.3103, 689.6552, 700.0000), "y"=c(0.0158, 0.0373, 0.0379, 0.0303, 0.0250, 0.0212, 0.0234, 0.0295, 0.0329, 0.0364, 0.0469, 0.0678, 0.0851, 0.0693, 0.0508, 0.0482, 0.0617, 0.2510, 0.6570, 0.7360, 0.6690, 0.5810, 0.5060, 0.4390, 0.3640, 0.2980, 0.2390, 0.1480, 0.0496, 0.0122))

How can I fit a curve to this data and get and equation for it? I need to be able to access estimated values of y at any given value of x between 400 and 700. I also don't know much about curve fitting; I just looked around and saw it looks like a lognormal shaped curve but couldn't figure out how to do it.

If the only reason to do this is to estimate y values given x values we could use loess or a gam. It may be necessary to play around with the span argument of loess.

plot(DF)
rng <- range(DF$x)
xx <- seq(rng[1], rng[2], length = 100)

lo <- loess(y ~ x, DF, span = 0.3)
lines(predict(lo, data.frame(x = xx)) ~ xx)

library(mgcv) # mgcv comes with R.  No need to install. Just load.
ga <- gam(y ~ s(x, bs = "cs"), data = DF)
lines(predict(ga, data.frame(x = xx)) ~ xx, col = 2, lty = 2)

legend("topleft", legend = c("loess", "gam"), lty = 1:2, col = 1:2)

截屏

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