Description Usage Arguments Value See Also Examples
Fits bilinear model to set of x,y points.
1 | best_fit_bilinear(x.vec, y.vec, truncate.left = 0, truncate.right = 0)
|
x.vec |
numeric vector of x coordinates |
y.vec |
numeric vector of y coordinates, must be the same length as x |
truncate.left |
positive integer - number of points to exclude from left hand side |
truncate.right |
positive integer - number of points to exclude from right hand side |
list with two componenets: numeric 2 by 2 matrix of coefficients, where row indicate model (left or right) and columns are intercept and slope; numeric vector intersection.x with: x coordinate of first point in left model closest to y (from right hand side), x coordinate of intersection point between left and right models and x coordinate of first point in right model closest to y (from left hand side); these points may be used as cutoff
The code was taken from https://stackoverflow.com/questions/15874214/piecewise-function-fitting-with-nls-in-r (with minor modifications).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # fix parameters of left linear model
a.left <- 0
b.left <- 0.8
# fix parameters of right linear model
a.right <- 15
b.right <- 0.1
# make models
x.left <- 1:20
y.left <- a.left + b.left * x.left
x.right <- 25:45
y.right <- a.right + b.right * x.right
# add some noise
y.left <- y.left + rnorm(length(y.left))
y.right <- y.right + rnorm(length(y.right))
# get y vector
x <- c(x.left, x.right)
y <- c(y.left, y.right)
# find best fit bilinear model
bf.model <- best_fit_bilinear(x, y)
print(bf.model[["coefficients"]])
print(bf.model[["intersection.x"]])
# plot results: points
plot(x, y, cex = 0.1)
# plot left model
abline(a = a.left, b = b.left, col = "blue")
# plot right model
abline(a = a.right, b = b.right, col = "green")
# plot left model fit
abline(a = bf.model[["coefficients"]]["left","intercept"], b = bf.model[["coefficients"]]["left","slope"], col = "blue", lty = 2)
# plot left model fit
abline(a = bf.model[["coefficients"]]["right","intercept"], b = bf.model[["coefficients"]]["right","slope"], col = "green", lty = 2)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.