Last active
July 20, 2016 14:54
-
-
Save duncanwerner/444df4981274eefc8b4aa287138569d5 to your computer and use it in GitHub Desktop.
Fit polynomial in Excel with BERT/R.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# fit a polynomial. pass a range of x (independent), | |
# y (dependent), and degree. | |
# | |
# returns a row vector by default, but pass False as | |
# the last parameter and it will return a column vector. | |
# | |
fit.poly <- function( x, y, degree, as.row=T ){ | |
x <- unlist(as.numeric(x)); | |
y <- unlist(as.numeric(y)); | |
model <- lm( y ~ poly(x, degree=degree, raw=T )); | |
if( as.row ){ | |
matrix( model$coefficients, nrow=1 ); | |
} | |
else { | |
model$coefficients; | |
} | |
} | |
# | |
# fit a polynomial using normal equation | |
# | |
fit.poly.ne <- function( x, y, degree, as.row=T ){ | |
x <- unlist(as.numeric(x)); | |
y <- unlist(as.numeric(y)); | |
X <- sapply( 0:degree, function(p){ x^p; }) | |
coeff <- solve( t(X) %*% X ) %*% t(X) %*% y; | |
if( as.row ){ matrix( coeff, nrow=1 ); } | |
else { coeff; } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment