How does apply() function works in R with example?

apply() function in R

In R programming, the apply() function is applied to a matrix, array, or data frame in a specified margin (i.e., row or column). The apply() function takes three arguments:

  1. The data structure to be operated on.
  2. The margin (1 for rows, 2 for columns).
  3. The function to be applied.

Parameters

  1. X: matrix, array, or data frame to operate on.
  2. MARGIN: The margin along which the function is to be applied (i.e., 1 for rows or 2 for columns).
  3. FUN: The function to apply to the matrix, array, or data frame.

Return Value

The apply() function returns a matrix or an array, depending on the input data structure and the margin specified. If MARGIN=1, the function returns a vector or matrix, where each row corresponds to the output of the applied function for that row. If MARGIN=2, the function returns a vector or matrix, where each column corresponds to the output of the applied function for that column.

Code Example

Suppose you have a matrix of sales data, where each row represents a salesperson and each column represents a month. You want to calculate the total sales for each salesperson. Here’s how you can use apply() to achieve this:

# create sample data
sales_data <- matrix(c(1000, 2000, 1500, 3000, 2500, 2000, 4000, 3000, 3500, 2500, 3000, 3500), nrow=4)

# calculate total sales for each salesperson
sales_total <- apply(sales_data, 1, sum)
sales_total

Line#2: Creates a 4×3 matrix called sales_data containing sales data for 4 salespeople and 3 months. The matrix is created using the matrix() function, which takes a vector of values (c(1000, 2000, 1500, ...)), the number of rows (nrow=4), and other optional arguments.

Line#5, 6: calculates the total sales for each salesperson by applying the sum() function across the rows (MARGIN=1) of the sales_data matrix using the apply() function. The result is a vector containing the total sales for each salesperson, which is assigned to the sales_total variable. Finally, the sales_total vector is printed to the console.

Output

apply() function in r

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...