Skip to contents

Apply a function to each z group using group_modify()

Usage

var_group_modify(var_grp_df, .f, ..., .subgroup = TRUE, .progress = FALSE)

Arguments

var_grp_df

the var_grp dataframe

.f

a function with the signature function(x,y,z,...) if the default .subgroup=TRUE or of the form function(xy,z,...) if .subgroup=FALSE. If .subgroup=TRUE The function will be called once for each group and subgroup with the parameters x being the data as a dataframe with usually multiple rows, and y and z being single row dataframes contianing the current subgroup and group respectively. Is subgroup=FALSE then only the major grouping z is used and

...

Arguments passed on to dplyr::group_modify

.data

A grouped tibble

.keep

are the grouping variables kept in .x

.subgroup

in the grouped data frames also subgroup by the y columns

.progress

shoudl progress be reported with a progress bar.

Value

the transformed data as a plain dataframe

Examples

tmp = iris %>% dplyr::group_by(Species) %>% var_group(. ~ Petal.Width + Petal.Length)

tmp2 = tmp %>% var_group_modify(
  ~ {
    Sys.sleep(0.02)
    return(.x %>% dplyr::count())
  },
  .progress=TRUE
)
#> ■■■■■■■■■■■                       32% | ETA:  2s
#> ■■■■■■■■■■■■■■■■■■■■■■■■          78% | ETA:  1s
#> ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■  100% | ETA:  0s

tmp3 = tmp %>% var_group_modify(~ .x %>% dplyr::count(), .subgroup=FALSE)

# .f with 2 parameters:
tmp %>% var_group_modify(
  ~ {
    return(tibble::tibble(
      Sepal.Area = .y$Sepal.Length*.y$Sepal.Width,
      Max.Petal.Area = max(.x$Petal.Length*.x$Petal.Width),
      n = nrow(.x)
    ))
  }
) %>% dplyr::filter(n>1)
#> 3 group(s): Species.
#> (subgroup) Sepal.Length + Sepal.Width ~ Sepal.Area + Max.Petal.Area + n (data)
#> # A tibble: 21 × 6
#>    Species Sepal.Length Sepal.Width Sepal.Area Max.Petal.Area     n
#>    <fct>          <dbl>       <dbl>      <dbl>          <dbl> <int>
#>  1 setosa           4.7         3.2       15.0           0.32     2
#>  2 setosa           4.8         3         14.4           0.42     2
#>  3 setosa           4.8         3.4       16.3           0.38     2
#>  4 setosa           4.9         3.1       15.2           0.3      2
#>  5 setosa           5           3.4       17             0.64     2
#>  6 setosa           5           3.5       17.5           0.96     2
#>  7 setosa           5.1         3.5       17.8           0.42     2
#>  8 setosa           5.1         3.8       19.4           0.76     3
#>  9 setosa           5.4         3.4       18.4           0.6      2
#> 10 setosa           5.4         3.9       21.1           0.68     2
#> # ℹ 11 more rows