logo

Función Apply(), lapply(), sapply(), tapply() en R con ejemplos

Aplicar() Función en R:

La aplicación de una función a una matriz, matriz o lista se realiza en R usando la función apply(). Es una función extremadamente útil para realizar acciones sobre los datos guardados en estas estructuras.

La siguiente es la sintaxis de la función apply():

aplicar(X, MARGEN, DIVERSIÓN, ...)

Aquí;

  • El margen al que se debe aplicar la función se especifica mediante el parámetro MARGIN. Puede ser un vector de estos valores, como 1, 2 o ambos para filas y columnas.
  • X es la matriz, matriz o lista sobre la que se está operando.
  • DIVERSIÓN es el resultado deseado.
  • Los argumentos opcionales de la función están contenidos en '... '.

Aquí hay algunos ejemplos de aplicar():

Ejemplo 1: aplicar una función a una matriz por filas

Digamos que tenemos la matriz que se muestra a continuación:

 m <- matrix(1:12, nrow="3)" < pre> <p>Apply() can be used to determine the mean of each row:</p> <pre> apply(m, 1, mean) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p> <strong>Example 2: Applying a Function to a Matrix by Columns</strong> </p> <p>Apply() can be used to determine the standard deviation for each column of a matrix m:</p> <pre> apply(m, 2, sd) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-2.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p> <strong>Example 3: Applying a Function to a List</strong> </p> <p>Consider a list of vectors:</p> <pre> lst <- list(a="1:5," b="6:10," c="11:15)" < pre> <p>Apply() can be used to determine the sum of each vector:</p> <pre> apply(lst, 1, sum) </pre> <p> <strong>Output:</strong> </p> <p>The sum of each vector in the list will be reported in this way:</p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-3.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <h4>Note: Due to the fact that we want to apply the function to each vector in the list, we use 1 as the value of MARGIN in this instance (i.e., along the first margin).</h4> <p> <strong>Example 4: Applying a User-Defined Function to a Matrix by Rows</strong> </p> <p>Let&apos;s say we have the matrix shown below:</p> <pre> m <- matrix(1:12, nrow="3)" < pre> <p>Apply() allows us to apply a user-defined function to each row:</p> <pre> f <- function(x) sum(x^2) apply(m, 1, f) < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-4.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The f() function computes the sum of the squares for each row in this example.</p> <p>All things considered, apply() is a fairly strong function that can be applied in a number of different ways to manipulate matrices, arrays, and lists.</p> <h2>lapply() Function in R:</h2> <p>A useful feature of the R programming language is the lapply() function, which enables you to apply a specific function to each element in a list or vector. A list with the same length as the input is produced as the output, with each entry representing the outcome of applying the specified function to its corresponding input element.</p> <p>The lapply() function&apos;s underlying syntax is as follows:</p> <pre> lapply(X, FUN, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. You can add more parameters to the FUN function by passing them as the &apos;... argument.&apos;</p> <h3>Some Examples of lapply():</h3> <p> <strong>Example 1:</strong> </p> <p>Let&apos;s look at an illustration of how to employ R&apos;s lapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. Each element of the list can have the sqrt() function applied to it using the lapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using lapply() result <- lapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-5.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sqrt() function was applied to each element of the list by the lapply() function, which then returned a list that had the same length as the input and contained elements that were the square roots of the corresponding input elements.</p> <p> <strong>Example 2:</strong> </p> <p>The lapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using lapply() result <- lapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-6.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the add 10() function was applied to each element of the list by the lapply() function, which resulted in a list that had the same length as the input and contained each element as the result of adding 10 to its corresponding input element.</p> <p>It&apos;s significant to remember that, regardless of the input, the lapply() method always produces a list. For instance, the result of using the lapply() method on a vector is still a list: Here is an example to show this.</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using lapply() result <- lapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-7.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sqrt() function was used after the lapply() method transformed the input vector into a list.</p> <h2>sapply() Function in R:</h2> <p>A helpful feature of the R programming language is the sapply() function, which may be used to streamline the code for applying a specified function to each element of a list or vector. A vector or matrix with the same length or dimensions as the input is produced as the output, with each element the outcome of applying the specified function to its corresponding input element.</p> <p>The sapply() function&apos;s syntax is as follows:</p> <pre> sapply(X, FUN, simplify = TRUE, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. By default, the simplified parameter is set to TRUE, meaning that if the function&apos;s output is a vector or matrix, the result will also be a vector or matrix. To send more arguments to the FUN function, use the &apos;... argument.&apos;</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s sapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. The sqrt() function can be applied to each element of the list using the sapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using sapply() result <- sapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-8.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sapply() method took each element of the list and applied the sqrt() function to it. It then returned a vector with the same length as the input, each element of which was the square root of its corresponding input element.</p> <p>The sapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using sapply() result <- sapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-9.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sapply() function added 10 to each element of the list using the add 10() function, returning a vector with the same length as the input where each element was the result of the addition of 10.</p> <p>It&apos;s crucial to remember that the sapply() function also works with vectors. In this situation, a vector will still be the result:</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using sapply() result <- sapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-10.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The sapply() method in this situation treated the input vector as a list and applied the sqrt() function to each element, returning a vector with the same length as the input and each element being the square root of its corresponding input element.</p> <h2>tapply() Function in R:</h2> <p>For applying a specified function to subsets of a vector or array based on the values of another variable, the R language&apos;s tapply() function is a helpful tool. Depending on the function used, the output is a vector, array, or list.</p> <p>The tapply() function&apos;s fundamental syntax is as follows:</p> <p>tapply(X, INDEX, FUN, ...)</p> <p>Here, FUN is the function to be applied to each subset, X is the input vector or array, INDEX is a factor or list of factors denoting the subsets, and... are optional parameters that can be supplied to the function FUN.</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s tapply() function.</p> <p>Assume we have a vector of categories and a vector of numbers. The average of the values for each category is what we are looking for.</p> <p>The mean() function can be applied to each subset of the vector based on the category using the tapply() function. The code is here;</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers numbers <- c(23, 18, 25, 32, 20, 19, 27, 31, 22, 24) # create a vector of categories <- c('a', 'b', 'a', 'a') apply the mean() function to each subset based on category using tapply() result tapply(numbers, categories, mean) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-11.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the tapply() function used the mean() function to analyze each subset of the vector according to the category, returning a named vector with the results for each category.</p> <h2>Conclusion:</h2> <p>Simplified vectors or matrices with the same lengths or dimensions as the input can be obtained by applying a given function to each element of a list or vector using R&apos;s sapply() function.</p> <p>Developing code can save a lot of time and effort, especially when working with large datasets. Moreover, the sapply() method is a flexible function that may be used with lists, vectors, and built-in and user-defined functions.</p> <p>Everyone working with R and dealing with data processing and analysis should be familiar with this function.</p> <hr></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></->

Producción:

descanso java
Función Apply(), lapply(), sapply(), tapply() en R con ejemplos

Ejemplo 2: aplicar una función a una matriz por columnas

Apply() se puede utilizar para determinar la desviación estándar de cada columna de una matriz m:

 apply(m, 2, sd) 

Producción:

Función Apply(), lapply(), sapply(), tapply() en R con ejemplos

Ejemplo 3: aplicar una función a una lista

CSS flotante

Considere una lista de vectores:

 lst <- list(a="1:5," b="6:10," c="11:15)" < pre> <p>Apply() can be used to determine the sum of each vector:</p> <pre> apply(lst, 1, sum) </pre> <p> <strong>Output:</strong> </p> <p>The sum of each vector in the list will be reported in this way:</p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-3.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <h4>Note: Due to the fact that we want to apply the function to each vector in the list, we use 1 as the value of MARGIN in this instance (i.e., along the first margin).</h4> <p> <strong>Example 4: Applying a User-Defined Function to a Matrix by Rows</strong> </p> <p>Let&apos;s say we have the matrix shown below:</p> <pre> m <- matrix(1:12, nrow="3)" < pre> <p>Apply() allows us to apply a user-defined function to each row:</p> <pre> f <- function(x) sum(x^2) apply(m, 1, f) < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-4.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The f() function computes the sum of the squares for each row in this example.</p> <p>All things considered, apply() is a fairly strong function that can be applied in a number of different ways to manipulate matrices, arrays, and lists.</p> <h2>lapply() Function in R:</h2> <p>A useful feature of the R programming language is the lapply() function, which enables you to apply a specific function to each element in a list or vector. A list with the same length as the input is produced as the output, with each entry representing the outcome of applying the specified function to its corresponding input element.</p> <p>The lapply() function&apos;s underlying syntax is as follows:</p> <pre> lapply(X, FUN, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. You can add more parameters to the FUN function by passing them as the &apos;... argument.&apos;</p> <h3>Some Examples of lapply():</h3> <p> <strong>Example 1:</strong> </p> <p>Let&apos;s look at an illustration of how to employ R&apos;s lapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. Each element of the list can have the sqrt() function applied to it using the lapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using lapply() result <- lapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-5.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sqrt() function was applied to each element of the list by the lapply() function, which then returned a list that had the same length as the input and contained elements that were the square roots of the corresponding input elements.</p> <p> <strong>Example 2:</strong> </p> <p>The lapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using lapply() result <- lapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-6.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the add 10() function was applied to each element of the list by the lapply() function, which resulted in a list that had the same length as the input and contained each element as the result of adding 10 to its corresponding input element.</p> <p>It&apos;s significant to remember that, regardless of the input, the lapply() method always produces a list. For instance, the result of using the lapply() method on a vector is still a list: Here is an example to show this.</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using lapply() result <- lapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-7.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sqrt() function was used after the lapply() method transformed the input vector into a list.</p> <h2>sapply() Function in R:</h2> <p>A helpful feature of the R programming language is the sapply() function, which may be used to streamline the code for applying a specified function to each element of a list or vector. A vector or matrix with the same length or dimensions as the input is produced as the output, with each element the outcome of applying the specified function to its corresponding input element.</p> <p>The sapply() function&apos;s syntax is as follows:</p> <pre> sapply(X, FUN, simplify = TRUE, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. By default, the simplified parameter is set to TRUE, meaning that if the function&apos;s output is a vector or matrix, the result will also be a vector or matrix. To send more arguments to the FUN function, use the &apos;... argument.&apos;</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s sapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. The sqrt() function can be applied to each element of the list using the sapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using sapply() result <- sapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-8.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sapply() method took each element of the list and applied the sqrt() function to it. It then returned a vector with the same length as the input, each element of which was the square root of its corresponding input element.</p> <p>The sapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using sapply() result <- sapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-9.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sapply() function added 10 to each element of the list using the add 10() function, returning a vector with the same length as the input where each element was the result of the addition of 10.</p> <p>It&apos;s crucial to remember that the sapply() function also works with vectors. In this situation, a vector will still be the result:</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using sapply() result <- sapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-10.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The sapply() method in this situation treated the input vector as a list and applied the sqrt() function to each element, returning a vector with the same length as the input and each element being the square root of its corresponding input element.</p> <h2>tapply() Function in R:</h2> <p>For applying a specified function to subsets of a vector or array based on the values of another variable, the R language&apos;s tapply() function is a helpful tool. Depending on the function used, the output is a vector, array, or list.</p> <p>The tapply() function&apos;s fundamental syntax is as follows:</p> <p>tapply(X, INDEX, FUN, ...)</p> <p>Here, FUN is the function to be applied to each subset, X is the input vector or array, INDEX is a factor or list of factors denoting the subsets, and... are optional parameters that can be supplied to the function FUN.</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s tapply() function.</p> <p>Assume we have a vector of categories and a vector of numbers. The average of the values for each category is what we are looking for.</p> <p>The mean() function can be applied to each subset of the vector based on the category using the tapply() function. The code is here;</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers numbers <- c(23, 18, 25, 32, 20, 19, 27, 31, 22, 24) # create a vector of categories <- c(\'a\', \'b\', \'a\', \'a\') apply the mean() function to each subset based on category using tapply() result tapply(numbers, categories, mean) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-11.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the tapply() function used the mean() function to analyze each subset of the vector according to the category, returning a named vector with the results for each category.</p> <h2>Conclusion:</h2> <p>Simplified vectors or matrices with the same lengths or dimensions as the input can be obtained by applying a given function to each element of a list or vector using R&apos;s sapply() function.</p> <p>Developing code can save a lot of time and effort, especially when working with large datasets. Moreover, the sapply() method is a flexible function that may be used with lists, vectors, and built-in and user-defined functions.</p> <p>Everyone working with R and dealing with data processing and analysis should be familiar with this function.</p> <hr></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></->

Producción:

La suma de cada vector de la lista se informará de esta manera:

Función Apply(), lapply(), sapply(), tapply() en R con ejemplos

Nota: Debido al hecho de que queremos aplicar la función a cada vector en la lista, usamos 1 como valor de MARGEN en este caso (es decir, a lo largo del primer margen).

Ejemplo 4: Aplicar una función definida por el usuario a una matriz por filas

Digamos que tenemos la matriz que se muestra a continuación:

 m <- matrix(1:12, nrow="3)" < pre> <p>Apply() allows us to apply a user-defined function to each row:</p> <pre> f <- function(x) sum(x^2) apply(m, 1, f) < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-4.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The f() function computes the sum of the squares for each row in this example.</p> <p>All things considered, apply() is a fairly strong function that can be applied in a number of different ways to manipulate matrices, arrays, and lists.</p> <h2>lapply() Function in R:</h2> <p>A useful feature of the R programming language is the lapply() function, which enables you to apply a specific function to each element in a list or vector. A list with the same length as the input is produced as the output, with each entry representing the outcome of applying the specified function to its corresponding input element.</p> <p>The lapply() function&apos;s underlying syntax is as follows:</p> <pre> lapply(X, FUN, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. You can add more parameters to the FUN function by passing them as the &apos;... argument.&apos;</p> <h3>Some Examples of lapply():</h3> <p> <strong>Example 1:</strong> </p> <p>Let&apos;s look at an illustration of how to employ R&apos;s lapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. Each element of the list can have the sqrt() function applied to it using the lapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using lapply() result <- lapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-5.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sqrt() function was applied to each element of the list by the lapply() function, which then returned a list that had the same length as the input and contained elements that were the square roots of the corresponding input elements.</p> <p> <strong>Example 2:</strong> </p> <p>The lapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using lapply() result <- lapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-6.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the add 10() function was applied to each element of the list by the lapply() function, which resulted in a list that had the same length as the input and contained each element as the result of adding 10 to its corresponding input element.</p> <p>It&apos;s significant to remember that, regardless of the input, the lapply() method always produces a list. For instance, the result of using the lapply() method on a vector is still a list: Here is an example to show this.</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using lapply() result <- lapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-7.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sqrt() function was used after the lapply() method transformed the input vector into a list.</p> <h2>sapply() Function in R:</h2> <p>A helpful feature of the R programming language is the sapply() function, which may be used to streamline the code for applying a specified function to each element of a list or vector. A vector or matrix with the same length or dimensions as the input is produced as the output, with each element the outcome of applying the specified function to its corresponding input element.</p> <p>The sapply() function&apos;s syntax is as follows:</p> <pre> sapply(X, FUN, simplify = TRUE, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. By default, the simplified parameter is set to TRUE, meaning that if the function&apos;s output is a vector or matrix, the result will also be a vector or matrix. To send more arguments to the FUN function, use the &apos;... argument.&apos;</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s sapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. The sqrt() function can be applied to each element of the list using the sapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using sapply() result <- sapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-8.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sapply() method took each element of the list and applied the sqrt() function to it. It then returned a vector with the same length as the input, each element of which was the square root of its corresponding input element.</p> <p>The sapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using sapply() result <- sapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-9.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sapply() function added 10 to each element of the list using the add 10() function, returning a vector with the same length as the input where each element was the result of the addition of 10.</p> <p>It&apos;s crucial to remember that the sapply() function also works with vectors. In this situation, a vector will still be the result:</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using sapply() result <- sapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-10.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The sapply() method in this situation treated the input vector as a list and applied the sqrt() function to each element, returning a vector with the same length as the input and each element being the square root of its corresponding input element.</p> <h2>tapply() Function in R:</h2> <p>For applying a specified function to subsets of a vector or array based on the values of another variable, the R language&apos;s tapply() function is a helpful tool. Depending on the function used, the output is a vector, array, or list.</p> <p>The tapply() function&apos;s fundamental syntax is as follows:</p> <p>tapply(X, INDEX, FUN, ...)</p> <p>Here, FUN is the function to be applied to each subset, X is the input vector or array, INDEX is a factor or list of factors denoting the subsets, and... are optional parameters that can be supplied to the function FUN.</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s tapply() function.</p> <p>Assume we have a vector of categories and a vector of numbers. The average of the values for each category is what we are looking for.</p> <p>The mean() function can be applied to each subset of the vector based on the category using the tapply() function. The code is here;</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers numbers <- c(23, 18, 25, 32, 20, 19, 27, 31, 22, 24) # create a vector of categories <- c(\'a\', \'b\', \'a\', \'a\') apply the mean() function to each subset based on category using tapply() result tapply(numbers, categories, mean) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-11.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the tapply() function used the mean() function to analyze each subset of the vector according to the category, returning a named vector with the results for each category.</p> <h2>Conclusion:</h2> <p>Simplified vectors or matrices with the same lengths or dimensions as the input can be obtained by applying a given function to each element of a list or vector using R&apos;s sapply() function.</p> <p>Developing code can save a lot of time and effort, especially when working with large datasets. Moreover, the sapply() method is a flexible function that may be used with lists, vectors, and built-in and user-defined functions.</p> <p>Everyone working with R and dealing with data processing and analysis should be familiar with this function.</p> <hr></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></->

En este caso, FUN es la función que se aplicará a cada miembro de X. X es la lista o vector de entrada. Puede agregar más parámetros a la función FUN pasándolos como el argumento '...'.

recorrido del árbol

Algunos ejemplos de lapply():

Ejemplo 1:

Veamos una ilustración de cómo emplear la función lapply() de R.

Digamos que queremos determinar la raíz cuadrada de cada número en una lista de números. A cada elemento de la lista se le puede aplicar la función sqrt() utilizando el método lapply(). Aquí está la clave:

Código:

 # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using lapply() result <- lapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-5.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sqrt() function was applied to each element of the list by the lapply() function, which then returned a list that had the same length as the input and contained elements that were the square roots of the corresponding input elements.</p> <p> <strong>Example 2:</strong> </p> <p>The lapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using lapply() result <- lapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-6.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the add 10() function was applied to each element of the list by the lapply() function, which resulted in a list that had the same length as the input and contained each element as the result of adding 10 to its corresponding input element.</p> <p>It&apos;s significant to remember that, regardless of the input, the lapply() method always produces a list. For instance, the result of using the lapply() method on a vector is still a list: Here is an example to show this.</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using lapply() result <- lapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-7.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sqrt() function was used after the lapply() method transformed the input vector into a list.</p> <h2>sapply() Function in R:</h2> <p>A helpful feature of the R programming language is the sapply() function, which may be used to streamline the code for applying a specified function to each element of a list or vector. A vector or matrix with the same length or dimensions as the input is produced as the output, with each element the outcome of applying the specified function to its corresponding input element.</p> <p>The sapply() function&apos;s syntax is as follows:</p> <pre> sapply(X, FUN, simplify = TRUE, ...) </pre> <p>In this case, FUN is the function that will be applied to each member of X. X is the input list or vector. By default, the simplified parameter is set to TRUE, meaning that if the function&apos;s output is a vector or matrix, the result will also be a vector or matrix. To send more arguments to the FUN function, use the &apos;... argument.&apos;</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s sapply() function.</p> <p>Let&apos;s say we want to determine the square root of each number in a list of numbers. The sqrt() function can be applied to each element of the list using the sapply() method. Here is the key:</p> <p> <strong>Code:</strong> </p> <pre> # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using sapply() result <- sapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-8.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sapply() method took each element of the list and applied the sqrt() function to it. It then returned a vector with the same length as the input, each element of which was the square root of its corresponding input element.</p> <p>The sapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using sapply() result <- sapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-9.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sapply() function added 10 to each element of the list using the add 10() function, returning a vector with the same length as the input where each element was the result of the addition of 10.</p> <p>It&apos;s crucial to remember that the sapply() function also works with vectors. In this situation, a vector will still be the result:</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using sapply() result <- sapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-10.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The sapply() method in this situation treated the input vector as a list and applied the sqrt() function to each element, returning a vector with the same length as the input and each element being the square root of its corresponding input element.</p> <h2>tapply() Function in R:</h2> <p>For applying a specified function to subsets of a vector or array based on the values of another variable, the R language&apos;s tapply() function is a helpful tool. Depending on the function used, the output is a vector, array, or list.</p> <p>The tapply() function&apos;s fundamental syntax is as follows:</p> <p>tapply(X, INDEX, FUN, ...)</p> <p>Here, FUN is the function to be applied to each subset, X is the input vector or array, INDEX is a factor or list of factors denoting the subsets, and... are optional parameters that can be supplied to the function FUN.</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s tapply() function.</p> <p>Assume we have a vector of categories and a vector of numbers. The average of the values for each category is what we are looking for.</p> <p>The mean() function can be applied to each subset of the vector based on the category using the tapply() function. The code is here;</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers numbers <- c(23, 18, 25, 32, 20, 19, 27, 31, 22, 24) # create a vector of categories <- c(\'a\', \'b\', \'a\', \'a\') apply the mean() function to each subset based on category using tapply() result tapply(numbers, categories, mean) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-11.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the tapply() function used the mean() function to analyze each subset of the vector according to the category, returning a named vector with the results for each category.</p> <h2>Conclusion:</h2> <p>Simplified vectors or matrices with the same lengths or dimensions as the input can be obtained by applying a given function to each element of a list or vector using R&apos;s sapply() function.</p> <p>Developing code can save a lot of time and effort, especially when working with large datasets. Moreover, the sapply() method is a flexible function that may be used with lists, vectors, and built-in and user-defined functions.</p> <p>Everyone working with R and dealing with data processing and analysis should be familiar with this function.</p> <hr></-></pre></-></pre></-></pre></-></pre></-></pre></-></pre></->

En este caso, FUN es la función que se aplicará a cada miembro de X. X es la lista o vector de entrada. De forma predeterminada, el parámetro simplificado está establecido en VERDADERO, lo que significa que si la salida de la función es un vector o una matriz, el resultado también será un vector o una matriz. Para enviar más argumentos a la función FUN, utilice el argumento '...'.

Veamos una ilustración de cómo emplear la función sapply() de R.

Digamos que queremos determinar la raíz cuadrada de cada número en una lista de números. La función sqrt() se puede aplicar a cada elemento de la lista utilizando el método sapply(). Aquí está la clave:

Código:

 # Create a list of numbers my_list <- list(4, 9, 16, 25) # apply the sqrt() function to each element of list using sapply() result <- sapply(my_list, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-8.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the sapply() method took each element of the list and applied the sqrt() function to it. It then returned a vector with the same length as the input, each element of which was the square root of its corresponding input element.</p> <p>The sapply() function can also be used with user-defined functions. Let&apos;s make a function that adds 10 to a given integer, for instance, and then use this function on each item in the list:</p> <p> <strong>Code:</strong> </p> <pre> # Define a function that adds 10 to a given number add_10 <- 10 function(x) { x + } # apply the add_10() function to each element of list using sapply() result <- sapply(my_list, add_10) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-9.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>In this instance, the sapply() function added 10 to each element of the list using the add 10() function, returning a vector with the same length as the input where each element was the result of the addition of 10.</p> <p>It&apos;s crucial to remember that the sapply() function also works with vectors. In this situation, a vector will still be the result:</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers my_vector <- c(4, 9, 16, 25) # apply the sqrt() function to each element of vector using sapply() result <- sapply(my_vector, sqrt) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-10.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>The sapply() method in this situation treated the input vector as a list and applied the sqrt() function to each element, returning a vector with the same length as the input and each element being the square root of its corresponding input element.</p> <h2>tapply() Function in R:</h2> <p>For applying a specified function to subsets of a vector or array based on the values of another variable, the R language&apos;s tapply() function is a helpful tool. Depending on the function used, the output is a vector, array, or list.</p> <p>The tapply() function&apos;s fundamental syntax is as follows:</p> <p>tapply(X, INDEX, FUN, ...)</p> <p>Here, FUN is the function to be applied to each subset, X is the input vector or array, INDEX is a factor or list of factors denoting the subsets, and... are optional parameters that can be supplied to the function FUN.</p> <p>Let&apos;s look at an illustration of how to employ R&apos;s tapply() function.</p> <p>Assume we have a vector of categories and a vector of numbers. The average of the values for each category is what we are looking for.</p> <p>The mean() function can be applied to each subset of the vector based on the category using the tapply() function. The code is here;</p> <p> <strong>Code:</strong> </p> <pre> # Create a vector of numbers numbers <- c(23, 18, 25, 32, 20, 19, 27, 31, 22, 24) # create a vector of categories <- c(\\'a\\', \\'b\\', \\'a\\', \\'a\\') apply the mean() function to each subset based on category using tapply() result tapply(numbers, categories, mean) print < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/r-tutorial/91/apply-lapply-sapply-11.webp" alt="Apply(), lapply(), sapply(), tapply() Function in R with Examples"> <p>As you can see, the tapply() function used the mean() function to analyze each subset of the vector according to the category, returning a named vector with the results for each category.</p> <h2>Conclusion:</h2> <p>Simplified vectors or matrices with the same lengths or dimensions as the input can be obtained by applying a given function to each element of a list or vector using R&apos;s sapply() function.</p> <p>Developing code can save a lot of time and effort, especially when working with large datasets. Moreover, the sapply() method is a flexible function that may be used with lists, vectors, and built-in and user-defined functions.</p> <p>Everyone working with R and dealing with data processing and analysis should be familiar with this function.</p> <hr></-></pre></-></pre></-></pre></->