Vectorizing a function means making it so that the function can take vector arguments and return a vector result. This is often done using the `mapply()` function, which takes a function and a list of arguments and applies the function to each combination of arguments.
For example, the following function computes the sum of squares for a given set of data:
sumsq <- function(x) {
sum((x - mean(x))^2)
}
This function can be vectorized by using the `mapply()` function:
sumsq_vec <- mapply(sumsq, x)
This will create a new function, `sumsq_vec`, that can take a vector of data as input and return a vector of sum of squares as output.
The `Vectorize()` function can also be used to vectorize a function. This function takes a function and a list of arguments that should be vectorized, and it returns a new function that is vectorized for those arguments.
For example, the following code vectorizes the `sumsq()` function for the `mu` and `sigma` arguments:
sumsq_vec <- Vectorize(sumsq, c("mu", "sigma"))
This will create a new function, `sumsq_vec`, that can take vectors of `mu` and `sigma` as input and return a vector of sum of squares as output.