R has built in functions like mean()
and
sum()
x <- 1:10
mean(x)
## [1] 5.5
sum(x)
## [1] 55
Let’s build a function which squares a number and adds 1: f(x) = x^2 +1.
square_plus_1 <- function(pen){
pen^2+1
}
square_plus_1(2)
## [1] 5
What happens when we apply square_plus_1 to the vector x from above?
square_plus_1(x)
## [1] 2 5 10 17 26 37 50 65 82 101
Build functions to compute RSS \[ RSS = \sum_{i=1}^n (y_i - \hat y_i)^2 \]
get_rss <- function(y, y_hat){
sum( (y - y_hat)^2 )
}
y <- c(1,2,3)
y_hat <- c(2,2, 0)
get_rss(y, y_hat)
## [1] 10