Skip to content

Instantly share code, notes, and snippets.

@duncanwerner
Last active July 20, 2016 14:54
Show Gist options
  • Save duncanwerner/444df4981274eefc8b4aa287138569d5 to your computer and use it in GitHub Desktop.
Save duncanwerner/444df4981274eefc8b4aa287138569d5 to your computer and use it in GitHub Desktop.
Fit polynomial in Excel with BERT/R.
#
# 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