apply family in r apply(), lapply(), sapply(), mapply() and tapply() (2024)

[This article was first published on Methods – finnstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

apply family in r, In this article, we are going to discuss the R Apply family. The apply family is an inbuilt R package, so no need to install any packages for the execution.

The main advantage of apply function is we can get rid of loop operations.

apply family in r contains apply(), lapply(), sapply(), mapply() and tapply().

How to clean the datasets in R? » janitor Data Cleansing »

One of the big questions is how and when to use these functions?

The answer is simple its depends on the structure of your data set and how you want the outcome.

Let’s see how to execute these functions one by one.

1. apply()

The syntax is

apply(X, MARGIN, FUN, …)

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

Let’s create a square matrix first and we want to evaluate the sum of each row.

mymatrix<-matrix(1:9,nrow=3)mymatrix[,1] [,2] [,3][1,] 1 4 7[2,] 2 5 8[3,] 3 6 9

Let’s calculate the row sum.

apply(mymatrix,1,sum) [1] 12 15 18

Let’s calculate the column sum

apply(mymatrix,2,sum) [1] 6 15 24

Let’s create NA value in the matrix and see how we can execute the function.

mymatrix[2,3]<-NA[,1] [,2] [,3][1,] 1 4 7[2,] 2 5 NA[3,] 3 6 9apply(mymatrix,1,sum)[1] 12 NA 18

Insert na.rm function in the above code and see the result.

apply(mymatrix,1,sum,na.rm=TRUE)[1] 12 7 18

This is one small example, the same way you can make use of apply() function in R.

2. lapply()

lapply(X, FUN,…)

lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.

LSTM Network in R » Recurrent Neural network »

lapply not required the margin. Let’s see an example for lapply.

First we need to create a list.

mylist<-list(A=matrix(1:9,nrow=3),B=1:5,C=8)mylist$A [,1] [,2] [,3][1,] 1 4 7[2,] 2 5 8[3,] 3 6 9$B[1] 1 2 3 4 5$C[1] 8

Let’s calculate the sum of each list.

lapply(mylist,sum)$A[1] 45$B[1] 15$C[1] 8

You can see how the results are saved as a list form. Suppose if you want vector result just unlist the same.

Linear optimization using R » Optimal Solution »

unlist(lapply(mylist,sum))A B C45 15 8

You can create your own functions and ppass into the function.

For example, suppose if you want multiply each element with value 20 just use the below code.

lapply(mylist,function(x) x*20)$A [,1] [,2] [,3][1,] 20 80 140[2,] 40 100 160[3,] 60 120 180$B[1] 20 40 60 80 100$C[1] 160

The same way, you can utilize lapply in different cases.

3. sapply()

sapply is a user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = “array”, an array if appropriate, by applying simplify2array(). sapply(x, f, simplify = FALSE, USE.NAMES = FALSE) is the same as lapply(x, f).

Logistic Regression R- Tutorial » Detailed Overview »

sapply(mylist,sum)

it follows the same job in laaply instead of list this function can handle vector.

A B C45 15 8

4. mapply()

maaply(FUN, …)

m stands for multi-variant apply.

Let’s take an example to suppose we have replicate values of 1 of four times and we want to replicate 1 at 4 times, 2 at 3 times, 3 at 2 times, and 4 at 1 time.

mapply(rep,1:4,4:1)[[1]][1] 1 1 1 1[[2]][1] 2 2 2[[3]][1] 3 3[[4]][1] 4

Let’s create a user-defined function and see how mapply will perform.

Suppose if we have two vectors x and y.

x<-c(A=20,B=1,C=40) y<-c(J=430,K=50,L=10)

Imagine if you want to add these two vectors and multiply by 2. First, create the function and pass it into mapply.

simply<-function(u,v){ (u+v)*2}mapply(simply,x,y)A B C 900 102 100 

6. tapply()

Apply a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors.

Stock Prediction-Intraday Trading » With High Accuracy »

Let’s iris dataset for an example, suppose if we want to calculate the maximum value of sepal length for all groups.

tapply(iris$Sepal.Length,iris$Species,max)setosa versicolor virginica 5.8 7.0 7.9

Conclusion

apply:- Appy function over the margins of an array.

lapply:- Loop over a list and evaluate a function on each element

sapply:- Same as lapply but try to simply the result.

mapply:- Multivariate version of lapply

tapply:-apply a function over subsets of a vector.

Correlation Analysis Different Types of Plots in R »

The post apply family in r apply(), lapply(), sapply(), mapply() and tapply() appeared first on finnstats.

Related

To leave a comment for the author, please follow the link and comment on their blog: Methods – finnstats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

apply family in r apply(), lapply(), sapply(), mapply() and tapply() (2024)

FAQs

What is apply family in R? ›

Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.

What is the difference between Lapply and apply? ›

lapply , you see that the syntax looks like the apply() function. The difference is that: It can be used for other objects like dataframes, lists or vectors; and. The output returned is a list (which explains the “l” in the function name), which has the same number of elements as the object passed to it.

What is tapply() in R? ›

tapply() is used to apply a function over subsets of a vector. It is primarily used when we have the following circ*mstances: A dataset that can be broken up into groups (via categorical variables - aka factors) We desire to break the dataset up into groups. Within each group, we want to apply a function.

What is family function in R? ›

the function family accesses the family objects which are stored within objects created by modelling functions (e.g., glm ). … further arguments passed to methods.

What does the apply() function do? ›

apply() method. This function acts as a map() function in Python. It takes a function as an input and applies this function to an entire DataFrame. If you are working with tabular data, you must specify an axis you want your function to act on ( 0 for columns; and 1 for rows).

What does sapply () do? ›

The sapply function

Applies a function to elements in a list and returns the results in a vector, matrix or a list. When the argument simplify=F then the sapply function returns the results in a list just like the lapply function.

What is the use of Mapply function in R? ›

mapply function in R

mapply gives us a way to call a non-vectorized function in a vectorized way. It is a multivariate version of sapply. mapply applies FUN to the first elements of each … argument, the second elements, the third elements, and so on.

What is the Python equivalent of sapply in R? ›

sapply in R is equivalent to map in python. sapply(c(-1, 1), abs) in R is equivalent to map(abs, (-1, 1)) in Python. But map returns a map object, so you need to pass it to list() if you want a list. In Python, you can also use list comprehension [abs(i) for i in (-1, 1)] .

What is the difference between apply and Applymap? ›

'apply' can be used on both Series(Element-wise) and DataFrames(Rows or Columns), returns a new Dataframe or series. It can be used when applying a custom functionthat require multiple columns. 'applymap' is best when you need to perform element-wise transformation across the whole DataFrame.

Is Lapply faster than a loop? ›

14.3.

So let me summarize it lapply is better than loops but it's no where near the speed of a vectorized code. Let's talk about the fastest way to speed up your code.

What is the alternative to Lapply in R? ›

For loop functionals: friends of lapply()
  1. sapply() and vapply() , variants of lapply() that produce vectors, matrices, and arrays as output, instead of lists.
  2. Map() and mapply() which iterate over multiple input data structures in parallel.
  3. mclapply() and mcMap() , parallel versions of lapply() and Map() .

What does apply () do in R? ›

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.

What is the Lapply function to a list in R? ›

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.

What package is tapply in R? ›

tapply,Vector,ANY-method in the IRanges package for an example of a specific tapply method (defined for Vector objects). BiocGenerics for a summary of all the generics defined in the BiocGenerics package.

What is the apply function in R? ›

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.

What is the difference between Vapply and Lapply? ›

vapply() is an implementation of lapply() that assigns results to a vector (or matrix) of appropriate type instead of as a list.

Which member of the apply function family returns a single list? ›

lapply returns a list of the same length as X , each element of which is the result of applying FUN to the corresponding element of X .

What does Lapply do? ›

The lapply function

Applies a function to elements in a list or a vector and returns the results in a list. The lapply function becomes especially useful when dealing with data frames. In R the data frame is considered a list and the variables in the data frame are the elements of the list.

References

Top Articles
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 6351

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.