drumminactuary
drumminactuary

Reputation: 119

Fit power curve that goes through specified coordinates in r

I have the following x-y pairs:

x <- seq(.3, .7, by=0.01)
y <- .5 * (x**-2.5) + runif(n = 41, min = -0.25, max = 0.25)

I would like to find the parameters A and B of a curve with the form y-hat = A * (x ** B), such that the sum of the squared error between y and y-hat is minimized.

Furthermore, the curve must pass through the coordinates (0.7, 1.0). Thus I really only need to solve for A, since B = -log(A)/log(0.7).

I can do this easily in Excel with Solver, but writing my own algorithm to solve for A in R is beyond my current ability. I'm guessing a built in solution already exists anyway. I looked into the poweRlaw package but there doesn't appear to be a way to force the curve through a specified point.

Upvotes: 2

Views: 219

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226771

set.seed(101)
x <- seq(.3, .7, by=0.01)
y <- .5 * (x**-2.5) + runif(n = 41, min = -0.25, max = 0.25)

You need a reasonable starting point: you can get one by log-log regression.

m1 <- lm(log(y)~log(x))  ## hope all your data are positive
A_est  <- exp(coef(m1)[1])

Now you're ready to estimate:

n1 <- nls(y ~ A*x^(-log(A)/log(0.7)),start=list(A=A_est))
A <- coef(n1)
B <- -log(A)/log(0.7)
plot(x,y)
curve(A*x^B,add=TRUE,col="red")

Upvotes: 2

Related Questions