简体   繁体   中英

Fit a curve/model to 1/x data

I have a dataset that follows the pattern of a 1/x curve. I would like to fit a curve to the data with a model.

I have tried using a polynomial function, but it doesn't quite look right because the polynomial curves back up, whereas my data asymptotes at the bottom. I know that I'm just missing some terminology here, but how can I do the curve? Is there a name for the 1/x curve?

x<-rep(1:20)
y<-1/x

fit <- lm(y ~ poly(x, 2))
plot(x, y)
points(x, predict(fit), type="l", col="red", lwd=2)

示例图

It's not working because you're forcing it to be a 2-degree polynomial with poly(x, 2) .

You'll want to create some other variable that is the transformation of your x value, and then run the regression on that:

x <- rep(1:20)
transformedx <- 1/x

y <- 1/x

fit <- lm(y ~ transformedx)
plot(x, y)
points(x, predict(fit), type="l", col="red", lwd=2)

For compactness you can simply write the formula in the lm line using the I function as Mike.Gahan pointed out:

fit <- lm(y ~ I(1/x))

Naturally this will be a perfect fit because you're mapping a function onto itself, but I'm assuming that in reality your y values are coming from data source that isn't a perfect match to 1/x .

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