Dianafreedom
Dianafreedom

Reputation: 411

How to fit a line with fixed points? (in R)

I have a few point pairs and I want to fit a line for them in R. I am now using loess but its prediction also changes the value of the original points. I want to find a fit that can generate a line with these fixed points, not necessarily polynomial fit.

This is my original code:

height = c(0, 11000, 20000, 32000, 47000, 51000, 71000, 84852)
beta = c(-0.0065, 0, 0.001, 0.0028, 0, -0.0028, -0.002, 0)

heightseq = seq(0, 84900, 100)
loesssmooth <- loess(beta ~ height, degree = 2)
pred = predict(loesssmooth, data.frame(height = heightseq), se = T)
plot(height, beta, col = "gray")
lines(heightseq, pred$fit, lwd = 2)

Upvotes: 0

Views: 471

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73385

You are looking for interpolation.

## linear interpolation
linear <- approx(height, beta, xout = heightseq)
plot(linear, type = "l"); points(height, beta, col = 8)

## natural cubic spline interpolation
ncs <- spline(height, beta, xout = heightseq, method = "natural")
plot(ncs, type = "l"); points(height, beta, col = 8)

Upvotes: 2

Related Questions