R apply() Function

The apply() function in R is used to apply a function to the rows or columns of a data frame, matrix, or array and gives output as vector, list, or array.

Syntax

apply(X, MARGIN, FUN)

Parameters

  1. The X is either an arraymatrix, or data frame.
  2. The MARGIN parameter can take a value or range between 1 and 2 to define where to apply the function.
  3. The FUN parameter tells us which function to apply.

Example 1: Applying a function to each row of a data frame

Figure of Applying a function to each row of a data frame

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

result <- apply(df, 1, sum)
print(result)

Output

[1]  12  15  18

Example 2: Apply a function to each column of a data frame

Figure of using apply() function to apply a function to each column of a data frame

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

result <- apply(df, 2, sum)
print(result)

Output

col1  col2   col3
 6     15     24

Example 3: Applying a custom function

fun <- function(x, character = FALSE) {
  if (character == FALSE) {
    x^2
  } else {
    as.character(x^2)
  }
}

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

apply(df, c(1, 2), fun)

Output

      col1  col2   col3
[1,]   1    16     49
[2,]   4    25     64
[3,]   9    36     81

Example 4: Usage with a matrix

Figure of using the apply() function to apply a function to a matrix

From the figure, you can see that we used the apply() function to get the sum of the matrix column-wise.

mtrx <- matrix(data = c(1:9), nrow = 3, ncol = 3)

cat("After using apply() function", "\n")

result <- apply(mtrx, 2, sum)

print(result)

Output

After using apply() function
[1]  6  15  24

Example 5: Usage with an array

rv <- c(19, 21, 18)
rv2 <- c(11, 21, 46)
ra <- array(c(rv, rv2), dim = c(2, 3, 1))

print(ra)

cat("After using apply() function", "\n")
apply_array <- apply(ra, 1, sum)
print(apply_array)

Output

, , 1

    [,1] [,2] [,3]
[1,] 19   18   21
[2,] 21   11   46

After using apply() function
[1]  58   78

That’s it.

Related posts

sapply() function

lapply() function

rapply() function

Leave a Comment