r sapply syntax

sapply is a function in R that applies a specified function to each element of a vector or list. The syntax for sapply is as follows:

sapply(X, FUN, ...)
  • X is the vector or list to be processed.
  • FUN is the function to be applied to each element of X.
  • ... represents additional arguments that can be passed to the function FUN.

The steps involved in using sapply are as follows:

  1. Specify the input vector or list: In the first step, you need to specify the vector or list that you want to process. This can be done by assigning the vector or list to a variable. For example:
my_vector <- c(1, 2, 3, 4, 5)
  1. Define the function: Next, you need to define the function that you want to apply to each element of the vector or list. This can be done using the function keyword and specifying the desired function logic. For example, let's say we want to square each element of the vector:
square_function <- function(x) {
  return(x^2)
}
  1. Apply the function using sapply: Finally, you can apply the defined function to each element of the vector or list using the sapply function. Pass the vector or list as the first argument (X), and the defined function as the second argument (FUN). For example:
result <- sapply(my_vector, square_function)

The result will be a new vector containing the processed values, in this case, the squared values of the original vector.