What is the usage of sapply in the R language?

The sapply function in R language is a vectorized operation function that applies the same function to each element of a vector, list, or data frame, and returns a resulting vector, list, or data frame.

The format for using sapply is as follows:
sapply(X, FUN, …)
where X represents the vector, list, or data frame to be operated on; FUN represents the function to be applied; … represents additional parameters for the FUN function.

The function of `sapply` is similar to a for loop, but it is more succinct and efficient. It eliminates the need for explicitly writing loops, which improves code readability and execution efficiency.

The output of the sapply function is a vector, list, or data frame where each element is the result of applying the FUN function to the corresponding element of X. If FUN returns a scalar value, the output is a vector; if FUN returns a vector, list, or data frame, the output is a list or data frame.

For example, suppose we have a vector x, and we want to calculate the square of each element and return the result vector. This can be achieved using the sapply function:
x <- c(1, 2, 3, 4, 5) sapply(x, function(x) x^2)

The output results are: 1 4 9 16 25.

The sapply function can also be used to operate on each element of a list or data frame. For example, if we have a list x containing multiple vectors and we want to calculate the mean of each vector and return the results as a list, we can achieve this using the sapply function:
x <- list(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9)) sapply(x, mean)

The output will be: 2 5 8.

In conclusion, the sapply function is a commonly used vectorized operation function in the R language, which simplifies the process of applying a function to each element of a vector, list, or data frame, and returns the result as a vector, list, or data frame.

bannerAds