Silencio - 10 months ago 45

R Question

I'm new to R, and I am working with Polynomial linear regression. I have a vector of coefficients or weights and we can say (for simplicity)

`w <- c(1:9)`

I need to multiply each coefficient respectively by x^j where j goes from 0 to 8 and sum them to obtain a function to later plot eg: (1*x^0 + 2*x^1 + 3*x^2...). I know I can manually input these but if the linear combination is large it becomes tedious, I also know that I can use loes to do regression but for this exercise I need to do it myself. So is there a non-manual way to paste these coefficients and functions together to later use with curve()? I was thinking:

`curve(1*x^0 + 2*x^1 + 3*x^2...)`

becomes

`curve(function(x))`

where function(x) contains the function wanted?

Thanks in advance.

Answer Source

This should work

```
w <- c(1:9)
f <- function(x, coef){
n <- length(coef)
deg <- 0:(n-1)
sapply(x, function(x)sum(coef * x^deg))
}
curve(f(x, coef = w))
```

By using sapply, we allow the function to take a vector of any length. This allows the function to be passed on to `curve`

.