# Function output for each group and month

I have a function similar as given below.
I would like to get the mean for each group and month stored in a list.
I expected to get 36 outputs (12 for each GROUP) as a list.

``````library(dplyr)
set.seed(1000)
dat=data.frame(
a=sample(1000,180),
b=sample(1000,180),
group=rep(1:3, each=60),
month=rep(rep(1:12,each=5),3)
)

ab_function=function(grp,mon){
P=P[P\$group==grp,]
P1=P[P\$month==mon,]
var.smpl <- P1 %>%
mutate(ab=a*b)
rmvc=mean(var.smpl\$ab)
return(rmvc)
}
``````

how can I apply similar like lapply?

As you are using `dplyr` anyway: There are excellent functions for grouping and subsetting and applying functions to your data in that package. The key functions you need are `group_by()` and `group_map()`. As your usecase is however, very easy with the function you provided, we can use `summarise()` instead:

``````library(dplyr)
set.seed(1000)
dat=data.frame(
a=sample(1000,180),
b=sample(1000,180),
group=rep(1:3, each=60),
month=rep(rep(1:12,each=5),3)
)

dat %>%
group_by(group,month) %>% #define the cloumns to group by
summarise(rmvc = mean(a*b)) #for each group, the new rmc will be calculated

#> `summarise()` has grouped output by 'group'. You can override using the `.groups` argument.
#> # A tibble: 36 x 3
#> # Groups:   group 
#>    group month    rmvc
#>    <int> <int>   <dbl>
#>  1     1     1 116478.
#>  2     1     2 224635.
#>  3     1     3 210373.
#>  4     1     4 256364.
#>  5     1     5 272303.
#>  6     1     6 494188
#>  7     1     7 243766.
#>  8     1     8 225413.
#>  9     1     9 126456.
#> 10     1    10 308955.
#> # ... with 26 more rows
``````

Created on 2022-01-02 by the reprex package (v2.0.1)

For more complicated group-wise action (e.b. fitting a linear model to each subset) it could be useful to have a look at `group_map()`, for many usecases, however, `summarise()` is what you are looking for.
Hope this helps!

Best
Valentin

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.