How to call functions within a function appropriately

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)
}

See the FAQ: How to do a minimal reproducible example reprex for beginners for a better way to include code examples.

won't work because it will return the closure, not the evaluation, because k.fit require three parameters and none have been provided.

func1 <- function(x) x + 1
func1(1)
#> [1] 2
func2 <- function(x) x + 2
func2(1)
#> [1] 3
func3 <- function(x) func1(x) + func2(x)
func3(1)
#> [1] 5
func4 <- function(x) return(func1)
func4(1)
#> function(x) x + 1
#> <bytecode: 0x560889df48f0>

Also, if the intent not is to transliterate matlab code into R but to solve the underlying calculation, there are probably functions to do this more easily.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.