Eine Anleitung für apply(), lapply(), sapply() und tapply() in R (2024)

In diesem Tutorial werden die Unterschiede zwischen den integrierten R-Funktionen apply(), sapply(), lapply() und tapply() sowie Beispiele für die Verwendung der einzelnen Funktionen erläutert.

apply()

Verwenden Sie die Funktion apply(), wenn Sie eine Funktion auf die Zeilen oder Spalten einer Matrix oder eines Dataframes anwenden möchten.

Die grundlegende Syntax für die Funktion apply() lautet wie folgt:

apply(X, MARGIN, FUN)

  • X ist der Name der Matrix oder des Dataframes
  • MARGIN gibt an, über welche Dimension eine Operation ausgeführt werden soll (1 = Zeile, 2 = Spalte).
  • FUN ist die spezifische Operation, die Sie ausführen möchten (z. B. min, max, sum, mean usw.).

Der folgende Code zeigt einige Beispiele für apply() in Aktion.

#Erstellen Sie ein Dataframe mit drei Spalten und fünf Zeilendata <- data.frame (a = c (1, 3, 7, 12, 9), b = c (4, 4, 6, 7, 8), c = c (14, 15, 11, 10, 6))data# a b c# 1 1 4 14# 2 3 4 15# 3 7 6 11# 4 12 7 10# 5 9 8 6#Finden Sie die Summe jeder Zeileapply(data, 1, sum)# [1] 19 22 24 29 23#Finden Sie die Summe jeder Spalteapply(data, 2, sum)# a b c# 32 29 56 #Finden Sie den Mittelwert jeder Zeileapply(data, 1, mean)# [1] 6.333333 7.333333 8.000000 9.666667 7.666667#Finden Sie den Mittelwert jeder Spalte, auf eine Dezimalstelle gerundetround(apply(data, 2, mean), 1)# a b c# 6.4 5.8 11.2 #Finden Sie die Standardabweichung jeder Zeileapply(data, 1, sd)# [1] 6.806859 6.658328 2.645751 2.516611 1.527525#Finden Sie die Standardabweichung jeder Spalteapply(data, 2, sd)# a b c# 4.449719 1.788854 3.563706 

lapply()

Verwenden Sie die Funktion lapply(), wenn Sie eine Funktion auf jedes Element einer Liste, eines Vektors oder eines Dataframes anwenden und als Ergebnis eine Liste erhalten möchten.

Die grundlegende Syntax für die Funktion lapply() lautet wie folgt:

lapply (X, FUN)

  • X ist der Name der Liste, des Vektors oder des Dataframes
  • FUN ist die spezifische Operation, die Sie ausführen möchten

Der folgende Code zeigt einige Beispiele für die Verwendung von lapply() in den Spalten eines Datenframes.

#Erstellen Sie ein Datenframe mit drei Spalten und fünf Zeilendata <- data.frame (a = c (1, 3, 7, 12, 9), b = c (4, 4, 6, 7, 8), c = c (14, 15, 11, 10, 6))data# a b c# 1 1 4 14# 2 3 4 15# 3 7 6 11# 4 12 7 10# 5 9 8 6#Finden Sie den Mittelwert jeder Spalte und geben Sie die Ergebnisse als Liste zurücklapply(data, mean)# $a# [1] 6.4## $b# [1] 5.8## $c# [1] 11.2# Multiplizieren Sie die Werte in jeder Spalte mit 2 und geben Sie die Ergebnisse als Liste zurücklapply(data, function(data) data*2)# $a# [1] 2 6 14 24 18## $b# [1] 8 8 12 14 16## $c# [1] 28 30 22 20 12

Wir können auch lapply() verwenden, um Operationen an Listen auszuführen. Die folgenden Beispiele zeigen, wie das geht.

#Erstellen Sie eine Listex <- list(a=1, b=1:5, c=1:10) x# $a# [1] 1## $b# [1] 1 2 3 4 5## $c# [1] 1 2 3 4 5 6 7 8 9 10#Finden Sie die Summe aller Elemente in der Listelapply(x, sum)# $a# [1] 1## $b# [1] 15## $c# [1] 55#Finden Sie den Mittelwert jedes Elements in der Listelapply(x, mean)# $a# [1] 1## $b# [1] 3## $c# [1] 5.5# Multiplizieren Sie die Werte jedes Elements mit 5 und geben Sie die Ergebnisse als Liste zurücklapply(x, function(x) x*5)# $a# [fünfzehn## $b# [1] 5 10 15 20 25## $c# [1] 5 10 15 20 25 30 35 40 45 50

sapply()

Verwenden Sie die Funktion sapply(), wenn Sie eine Funktion auf jedes Element einer Liste, eines Vektors oder eines Datenframes anwenden und als Ergebnis einen Vektor anstelle einer Liste erhalten möchten.

Die grundlegende Syntax für die Funktion sapply() lautet wie folgt:

sapply (X, FUN)

  • X ist der Name der Liste, des Vektors oder des Dataframes
  • FUN ist die spezifische Operation, die Sie ausführen möchten

Der folgende Code zeigt einige Beispiele für die Verwendung von sapply() in den Spalten eines Datenframes.

#Erstellen Sie ein Dataframe mit drei Spalten und fünf Zeilendata <- data.frame(a = c (1, 3, 7, 12, 9), b = c (4, 4, 6, 7, 8), c = c (14, 15, 11, 10, 6))data# a b c# 1 1 4 14# 2 3 4 15# 3 7 6 11# 4 12 7 10# 5 9 8 6#Mittelwert jeder Spalte finden und Ergebnisse als Vektor zurückgebensapply(data, mean)# a b c# 6.4 5.8 11.2 #Multiplizieren Sie die Werte in jeder Spalte mit 2 und geben Sie die Ergebnisse als Matrix zurücksapply(data, function(data) data*2)# a b c# [1,] 2 8 28# [2,] 6 8 30# [3,] 14 12 22# [4,] 24 14 20# [5,] 18 16 12

Wir können auch sapply() verwenden, um Operationen an Listen auszuführen. Die folgenden Beispiele zeigen, wie das geht.

#Erstelle eine Listex <- list(a=1, b=1:5, c=1:10) x# $a# [1] 1## $b# [1] 1 2 3 4 5## $c# [1] 1 2 3 4 5 6 7 8 9 10#Finden Sie die Summe aller Elemente in der Listesapply(x, sum)# a b c# 1 15 55 #Finden Sie den Mittelwert jedes Elements in der Listesapply(x, mean)# a b c# 1.0 3.0 5.5

tapply()

Verwenden Sie die Funktion tapply(), wenn Sie eine Funktion auf Teilmengen eines Vektors anwenden möchten und die Teilmengen durch einen anderen Vektor definiert werden, normalerweise einen Faktor.

Die grundlegende Syntax für die Funktion tapply() lautet wie folgt:

tapply (X, INDEX, FUN)

  • X ist der Name des Objekts, normalerweise ein Vektor
  • INDEX ist eine Liste von einem oder mehreren Faktoren
  • FUN ist die spezifische Operation, die Sie ausführen möchten

Der folgende Code zeigt ein Beispiel für die Verwendung von tapply() für das integrierte R-Dataset iris.

#Die ersten sechs Zeilen des Iris-Datensatzes anzeigenhead(iris)# Sepal.Length Sepal.Width Petal.Length Petal.Width Species#1 5.1 3.5 1.4 0.2 setosa#2 4.9 3.0 1.4 0,2 setosa#3 4.7 3.2 1.3 0,2 setosa#4 4.6 3.1 1.5 0.2 setosa#5 5.0 3.6 1.4 0.2 setosa#6 5.4 3.9 1.7 0.4 setosa#Finden Sie die maximale Sepal.Länge jeder der drei Artentapply(iris$Sepal.Length, iris$Species, max)# setosa versicolor virginica # 5.8 7.0 7.9 #Finden Sie die mittlere Sepal.Width jeder der drei Artentapply(iris$Sepal.Width, iris$Species, mean)# setosa versicolor virginica # 3.428 2.770 2.974#Finden Sie das minimale Blütenblatt. Breite jeder der drei Artentapply(iris$Petal.Width, Iris$Species, min)# setosa versicolor virginica # 0.1 1.0 1.4 
Eine Anleitung für apply(), lapply(), sapply() und tapply() in R (2024)

FAQs

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 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 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.

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 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 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 applying Lapply function on a matrix returns ________? ›

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 . 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() .

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 is apply () in pandas? ›

The apply() method is one of the most common methods of data preprocessing. It simplifies applying a function on each element in a pandas Series and each row or column in a pandas DataFrame.

What is the difference between Tapply and aggregate in R? ›

aggregate is designed to work on multiple columns with one function and returns a dataframe with one row for each category, while tapply is designed to work on a single vector with results returned as a matrix or array.

What is %>% in R? ›

R pipes are a way to chain multiple operations together in a concise and expressive way. They are represented by the %>% operator, which takes the output of the expression on its left and passes it as the first argument to the function on its right. Using pipes in R allows us to link a sequence of analysis steps.

What is the difference between Sapply and Lapply? ›

The sapply() function is a simplified form of lapply() ("s" in the function name stands for "simplified"). It has the same syntax as lapply() (i.e., sapply(X, FUN) ); takes in a vector, a list, or a DataFrame as input, just as lapply() does, and tries to reduce the output object to the most simplified data structure.

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.

How to apply function in calculation? ›

the apply function looks like this: apply(X, MARGIN, FUN).
  1. X is an array or matrix (this is the data that you will be performing the function on)
  2. Margin specifies whether you want to apply the function across rows (1) or columns (2)
  3. FUN is the function you want to use.

What are alternatives to Lapply? ›

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

What is the difference between do call and Lapply? ›

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. do. call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

What is the difference between Lapply and Purrr map? ›

The base equivalent to map() is lapply() . The only difference is that lapply() does not support the helpers that you'll learn about below, so if you're only using map() from purrr, you can skip the additional dependency and use lapply() directly.

What is the apply () function? ›

The apply() method is one of the most common methods of data preprocessing. It simplifies applying a function on each element in a pandas Series and each row or column in a pandas DataFrame.

References

Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6349

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.