Why do we use apply() function in R?

This is used to apply the same function to each of the elements in an Array. For example, finding the mean of the rows in every row.

In R, the apply() function is used to apply a specified function to the rows or columns of a matrix or data frame. The primary purpose of using apply() is to simplify code and make it more concise when performing operations on rows or columns.

Here are some common reasons for using the apply() function in R:

Code Conciseness: Using apply() can often lead to more concise and readable code compared to using loops for similar operations.

Efficiency: The apply() function is implemented in a way that can be more efficient than explicit looping in R. It takes advantage of vectorization, which can result in faster execution times for certain operations.

Applying Functions to Rows or Columns: You can use apply() to apply a custom or built-in function to either rows (MARGIN = 1) or columns (MARGIN = 2) of a matrix or data frame. This can be useful for tasks such as calculating row-wise or column-wise sums, means, or other custom operations.

Handling Multidimensional Arrays: apply() can be applied not only to matrices and data frames but also to multidimensional arrays, allowing you to perform operations along specific dimensions.

Here’s a simple example of using apply() to calculate the row-wise sum of a matrix:
# Create a matrix
my_matrix <- matrix(1:9, nrow = 3)

# Use apply to calculate the row-wise sum
row_sums <- apply(my_matrix, MARGIN = 1, FUN = sum)

# Display the result
print(row_sums)
In this example, apply() is applied with MARGIN = 1 to calculate the sum of each row in the matrix my_matrix.