How to use the group_map method In R Language
The group_map() method can also apply a function to each group in the tibble. The method returns the number of tibbles equivalent to the number of groups returned. It has the following syntax :
Syntax: group_map(.data, .f, …, .keep = FALSE)
Arguments :
- .data – A grouped tibble
- .f – The function to be applied
The following code snippet illustrates the usage of the group_map() method on a grouped tibble, wherein user-defined entries are grouped based on column x values. The sum of column y values is computed against each tibble group value. A user-defined sum_y function is declared and defined, which returns the output as the sum of the input vector values.
R
# Importing dplyr library (dplyr) # Creating a tibble data = tibble ( x = c (2,4,5,6,2,5,6,6,2,6), y = 1:10) print ( "Data" ) print (data) sum_y = function (vector) { return (tibble:: tibble (sum = sum (vector))) } # Grouping the data by x and # then computing the group wise # sum using y column data %>% group_by (x) %>% group_map (~ sum_y (.x$y)) |
Output:
[1] "Data" > print(data) # A tibble: 10 × 2 x y <dbl> <int> 1 2 1 2 4 2 3 5 3 4 6 4 5 2 5 6 5 6 7 6 7 8 6 8 9 2 9 10 6 10 [[1]] # A tibble: 1 x 1 sum <int> 1 15 [[2]] # A tibble: 1 x 1 sum <int> 1 2 [[3]] # A tibble: 1 x 1 sum <int> 1 9 [[4]] # A tibble: 1 x 1 sum <int> 1 29
Apply a function to each group using Dplyr in R
In this article, we are going to learn how to apply a function to each group using dplyr in the R programming language.
The dplyr package in R is used for data manipulations and modifications. The package can be downloaded and installed into the working space using the following command :
install.packages("dplyr")