USING R PROGRAMMING: Polynomial fitting is a function approximation method yield
ID: 3712240 • Letter: U
Question
USING R PROGRAMMING:
Polynomial fitting is a function approximation method yielding a result with a polynomial format. R doesn't directly support polynomial fitting but we can achieve this functionality through lm . For the first question, you are given an almost complete function except the error located at the first line. You should find and correct it. Trapezoid method is one of the basic algorithms for numerical integration. For the second question, you are supposed to write an trapezoid integration function. Argument is the sequence of y values. Assume that unit spacing is used.
I. Questions
Write a function poly_fit <- function(x, y, n) . Arguments must be of the following form:
x : Initial data.
y : Corresponding function outputs.
n : Degree of the resulting polynomial. Return value: coefficients , the coefficients of the polynomial
Write a function trapezoid <- function(y) . Here are the arguments:
y : Function values. Return value: integration result.
II. Remarks When unit spacing is used, you can assume that x i + 1 - x i = 1 .
Explanation / Answer
Solution:
Note: More than one question asked.
Function poly_fit():
poly_fit <- function(x,y,n) {
pwrs <- powers(x,n)
lmt <- list()
# Build new class
class(lmt) <- "poly"
for (di in 1:n) {
lmp <- lm(y ~ pwrs[,1:di])
# Prediction of cross validat
lmp$fitted.xvvalues <- lvoneout(y,pwrs[,1:di,drop=F])
lmt[[di]] <- lmp
}
lmt$x <- x
lmt$y <- y
return(lmt)
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.