I am new to R and I have heard a lot about the apply function.

Can someone list down the advantages of apply function?

Thanks. Jul 9, 2018 201 views

## 2 answers to this question.

The apply function allows us to make entry-by-entry changes to data frames and matrices.

The usage in R is as follows:

apply(X, MARGIN, FUN, …)

where:

X is an array or matrix;

MARGIN is a variable that determines whether the function is applied over rows (MARGIN=1), columns (MARGIN=2), or both (MARGIN=c(1,2));

FUN is the function to be applied.

If MARGIN=1, the function accepts each row of X as a vector argument and returns a vector of the results. Similarly, if MARGIN=2 the function acts on the columns of X. Most impressively, when MARGIN=c(1,2) the function is applied to every entry of X.

With the apply function, we can edit every entry of a data frame with a single line command. No auto-filling, no wasted CPU cycles. answered Jul 9, 2018 by
• 3,720 points

apply

Description: “Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.”

We know about vectors/arrays and functions, but what are these “margins”?

Simple: either the rows (1), the columns (2) or both (1:2). By “both”, we mean “apply the function to each individual value.” An example:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # create a matrix of 10 rows x 2 columns m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2) # mean of the rows apply(m, 1, mean)    6  7  8  9 10 11 12 13 14 15 # mean of the columns apply(m, 2, mean)   5.5 15.5 # divide all values by 2 apply(m, 1:2, function(x) x/2)       [,1] [,2]  [1,]  0.5  5.5  [2,]  1.0  6.0  [3,]  1.5  6.5  [4,]  2.0  7.0  [5,]  2.5  7.5  [6,]  3.0  8.0  [7,]  3.5  8.5  [8,]  4.0  9.0  [9,]  4.5  9.5 [10,]  5.0 10.0 answered Jul 10, 2018 by
• 3,790 points

## R function for finding the index of an element in a vector?

The function match works on vectors : x <- sample(1:10) x # ...READ MORE

+1 vote

## Which function can I use to clear the console in R and RStudio ?

Description                   Windows & Linux           Mac Clear console                      Ctrl+L ...READ MORE

## Why should I use set.seed function() in R?

set.seed(seed) Set the seed of R‘s random number ...READ MORE

## Python equivalent to replace function in R

There is actually a replace function in ...READ MORE

## Big Data transformations with R

Dear Koushik, Hope you are doing great. You can ...READ MORE

## Finding frequency of observations in R

You can use the "dplyr" package to ...READ MORE

The below is the code to perform ...READ MORE