Hi, I am new to building my own functions and require some assistance please?
I have produced two functions, the first produces a matrix from a vector x and a parameter theta and the second produces fitted y-values using the matrix outputted from the first function and a separate y vector.
I now want to produce a brand new separate function that combines the above 2 functions including all of the relevant parameters and outputs just the fitted y-values. How would I do this? See code below.
##Write function to produce the matrix##
k.matrix <- function(x, theta) {
n <- length(x)
K <- matrix(rep(0, n^2), nrow=n)
for(i in 1:n)
for (j in 1:n)
{K[i,j] <- exp(-(((x[i]-x[j])^2)/(rho^2)))}
K
}
k.matrix(x, theta)
##Write function to output fitted values using matrix, response variable and parameter xi##
library(matlib)
k.fit <- function(K, y, xi) {
I <- diag(length(x))
L <- K+xiI
Inv <- inv(L)%%y
yhat <- K%%Inv%%y
yhat
}
##Write third combined function including parameter default values and warning message##
k.combined <- function(x, y, theta=sd(x), xi=0.001) {
if (length(x)!=length(y)) {warning("The vectors x and y must have the same length.")}
return(k.fit)
}