• Post author:
  • Post category:R Programming
  • Post last modified:August 16, 2024
  • Reading time:10 mins read
You are currently viewing Explain apply() Function in R with Examples

The apply() function in R is used to apply a function to the rows or columns of a data frame or matrix. This function simplifies complex operations on matrices and data frames, making it easier to perform repetitive tasks without explicit loops.

Advertisements

The apply() function in R is a powerful tool used to apply a function to the margins of an array or matrix, such as rows or columns, and to simplify the result. It is part of the apply family of functions, which also includes lapply(), sapply(), and tapply().

In this article, I will explore the apply() function, detailing its syntax, parameters, and usage. We’ll demonstrate how to apply a specified function to process the rows or columns of a matrix or data frame.

Key points-

  • The apply() function can be used with various functions to process rows or columns of a matrix, or data frames.
  • This parameter specifies whether to apply the function to rows (MARGIN = 1), columns (MARGIN = 2), or both (MARGIN = c(1, 2)).
  • The result is a matrix, vector, or array obtained by applying the specified function.
  • The function simplifies the result based on the specified function.
  • You can define and apply custom functions within an apply() function.
  • The apply() function can be more memory efficient than using loops for similar operations.
  • It is flexible enough to handle various types of data and operations, making it a valuable tool for data analysis.

R apply() Function

The apply() function in R is versatile and can be used with various functions to process rows or columns of a matrix, or data frame. The MARGIN parameter specifies whether to apply the function to rows (MARGIN = 1) or columns (MARGIN = 2), and the FUN parameter specifies the function to apply.

Syntax of apply() Function

Following is the syntax of the apply() function.


# Synatx of apply() function
apply(X, MARGIN, FUN, ...)

Parameters

  • x: X is a matrix or data frame, representing the data on which the function will be performed.
  • MARGIN: An integer vector indicating which margins to apply the function to. 1 indicates rows, 2 indicates columns, and c(1, 2) indicates rows and columns.
  • FUN: Is the function you want to use

Return Value

  • The return value is a matrix, vector, or array obtained by applying the specified function to the margins of X.

Use apply() Function to Matrix Rows in R

Let’s create the matrix and use the apply() function on each row to get the result in a vector. To do this, pass the given matrix into the apply() function along with the MARGIN parameter set to 1 (indicating rows), and specify the desired function using the FUN parameter. This will apply the specified function to each row and return the result as a vector.


# Use apply() function to matrix rows
# Create a matrix
mat <- matrix(1:12, nrow = 3)
print("Given matrix:")
print(mat)
print("Get the type of given matrix:")
print(class(mat))
result <- apply(mat, MARGIN = 1, FUN = mean)
print("After applying apply function to matrix:")
print(result)

The apply() function has returned a numeric vector containing the means of each row in a given matrix.

Yields below output.

apply in r

Use apply() to Columns of Matrix in R

To apply this function to the columns of the matrix, you can set the MARGIN parameter to 2 along with the FUN parameter. This will apply the specified function to each column of the given matrix, resulting in a vector. Let’s set the MARGIN parameter to 2 and FUN to mean, and pass them into the apply() function to get the means of each column of the matrix.


# Use apply() function to matrix columns
# Create a matrix
mat <- matrix(1:12, nrow = 3)
print("Given matrix:")
print(mat)
print("Get the type of given matrix:")
print(class(mat))
result <- apply(mat, MARGIN = 2, FUN = mean)
print("After applying apply function to matrix:")
print(result)
print("Get the type of result:")
print(class(result))

Yields below output.

apply in r

Apply Function to Whole Matrix

Similarly, you can use the apply() function to process an entire matrix by specifying the MARGIN parameter with 1:2 (where 1 is for rows and 2 is for columns). Let’s apply a custom function to the entire matrix, processing each element, and return the result as a matrix.


# Apply function to whole matrix
# Create a matrix
mat <- matrix(1:12, nrow = 3)
result <- apply(mat, 1:2, function(x) x - 5)
print("After applying apply function to matrix:")
print(result)

# Output:
# [1] "After applying apply function to matrix:"
#      [,1] [,2] [,3] [,4]
# [1,]   -4   -1    2    5
# [2,]   -3    0    3    6
# [3,]   -2    1    4    7

The apply() function has returned a matrix where 5 has been subtracted from each element.

Apply Custom Function to Matrix Rows

Alternatively, you can use the apply() function to apply a custom function to the rows of a matrix. First, define the custom function, and then pass it to the apply() function along with the MARGIN and FUN parameters. This function will apply the custom function to each element in a row-wise manner and return the result as a matrix.


# Applying a Custom Function to Matrix Rows
# Define a custom function
cus_fun <- function(x) {
  return(x * 2)
}
# Use apply() function to matrix rows
# Create a matrix
mat <- matrix(1:12, nrow = 3)
result <- apply(mat, MARGIN = 1, FUN = cus_fun)
print("After applying custom function to matrix:")
print(result)

# Output:
# [1] "After applying custom function to matrix:"
#     [,1] [,2] [,3]
# [1,]    2    4    6
# [2,]    8   10   12
# [3,]   14   16   18
# [4,]   20   22   24

The apply() function has returned a matrix where each element is doubled.

Apply Function to Data Frame

You can also manipulate data frame rows, columns, or the entire data frame using the apply() function. Let’s create a data frame and use this function to operate over the rows of the data frame, obtaining the result in the form of a vector.


# Apply function to data frame rows
# Create a data frame
df <- data.frame(
  A = c(1, 2, 3),
  B = c(4, 5, 6),
  C = c(7, 8, 9)
)

print("Given data frame:")
print(df)
result <- apply(df, MARGIN = 1, FUN = mean)
print("After applying apply function to data frame:")
print(result)
print("Get the type of result:")
print(class(result))

# Output:
# [1] "Given data frame:"
#   A B C
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9

# [1] "After applying apply function to data frame:"
# [1] 4 5 6
# [1] "Get the type of result:"
# [1] "numeric"

This function has returned a numeric vector where the elements are the means of each row of the data frame.

Conclusion

The apply() function is a versatile and powerful tool in R, essential for performing operations on matrices or data frames. By allowing users to specify the margins and functions to apply, it provides a flexible way to process and manipulate data efficiently. Its ability to handle custom functions and its memory efficiency make it a crucial function for data analysis in R.

Happy learning !!