logo

Функція Apply(), lapply(), sapply(), tapply() у R із прикладами

Функція apply() в R:

Застосування функції до матриці, масиву або списку виконується в R за допомогою функції apply(). Це надзвичайно корисна функція для виконання дій над даними, що зберігаються в цих структурах.

Нижче наведено синтаксис функції apply():

застосувати (X, MARGIN, FUN, ...)

Тут;

  • Поле, до якого має бути застосована функція, визначається параметром MARGIN. Це може бути вектор цих значень, наприклад 1, 2 або обидва для рядків і стовпців.
  • X — це матриця, масив або список, з якими здійснюється операція.
  • Веселощі - це бажаний результат.
  • Необов’язкові аргументи функції містяться в '... '.

Ось кілька прикладів apply():

Приклад 1: Застосування функції до матриці за рядками

двійковий пошук

Припустимо, у нас є матриця, показана нижче:

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

Вихід:

Функція Apply(), lapply(), sapply(), tapply() у R із прикладами

Приклад 2: Застосування функції до матриці за стовпцями

Apply() можна використовувати для визначення стандартного відхилення для кожного стовпця матриці m:

з'єднання та типи з'єднань
 apply(m, 2, sd) 

Вихід:

Функція Apply(), lapply(), sapply(), tapply() у R із прикладами

Приклад 3: Застосування функції до списку

Розглянемо список векторів:

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

Вихід:

jquery одним клацанням миші

Сума кожного вектора в списку буде повідомлена таким чином:

Функція Apply(), lapply(), sapply(), tapply() у R із прикладами

Примітка. Через те, що ми хочемо застосувати функцію до кожного вектора в списку, ми використовуємо 1 як значення MARGIN у цьому випадку (тобто вздовж першого поля).

Приклад 4: Застосування визначеної користувачем функції до матриці за рядками

Припустимо, у нас є матриця, показана нижче:

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

У цьому випадку FUN — це функція, яка буде застосована до кожного члена X. X — вхідний список або вектор. Ви можете додати більше параметрів до функції FUN, передавши їх як аргумент '...'.

Деякі приклади lapply():

приклад 1:

Давайте подивимося на ілюстрацію того, як використовувати функцію lapply() R.

рівність об’єктів Java

Скажімо, ми хочемо визначити квадратний корінь з кожного числа в списку чисел. До кожного елемента списку може бути застосована функція sqrt() за допомогою методу lapply(). Ось ключ:

код:

 # 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></->

У цьому випадку FUN — це функція, яка буде застосована до кожного члена X. X — вхідний список або вектор. За замовчуванням для спрощеного параметра встановлено значення TRUE, що означає, що якщо результатом функції є вектор або матриця, результат також буде вектором або матрицею. Щоб надіслати додаткові аргументи функції FUN, використовуйте аргумент '....'

Давайте подивимося на ілюстрацію того, як використовувати функцію sapply() R.

java parseint

Скажімо, ми хочемо визначити квадратний корінь з кожного числа в списку чисел. Функцію sqrt() можна застосувати до кожного елемента списку за допомогою методу sapply(). Ось ключ:

код:

 # 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></->