Skip to contents

Create vector based on roughly equally sized groups

Usage

ntiles(
  x,
  n = 3,
  format = c("rank", "interval", "mean", "median", "center", "left", "right"),
  digits = 3
)

Arguments

x

a numeric vector

n

(approximate) number of quantiles

format

a specification of desired output format. One of "center", "interval", "left", "right", "mean", or "median.

digits

desired number of digits for labeling of factors.

Value

a vector. The type of vector will depend on format.

Details

This is a functional clone of mosaic::ntiles in order to avoid the dependency. It should be removed in the future, when there is no need to avoid such dependency, e.g. when {mosaic} is available on WASM.

Examples

FEV |> head(20) |> mutate(group = ntiles(height, 3, format="center"))
#> # A tibble: 20 × 6
#>      age   FEV height sex   smoker group
#>    <int> <dbl>  <dbl> <chr> <chr>  <dbl>
#>  1     9  1.71   57   F     not     57.2
#>  2     8  1.72   67.5 F     not     63.2
#>  3     7  1.72   54.5 F     not     52.2
#>  4     9  1.56   53   M     not     52.2
#>  5     9  1.90   57   M     not     57.2
#>  6     8  2.34   61   F     not     63.2
#>  7     6  1.92   58   F     not     57.2
#>  8     6  1.42   56   F     not     57.2
#>  9     8  1.99   58.5 F     not     57.2
#> 10     9  1.94   60   F     not     63.2
#> 11     6  1.60   53   F     not     52.2
#> 12     8  1.74   54   M     not     52.2
#> 13     8  2.19   58.5 F     not     57.2
#> 14     8  2.12   60.5 M     not     63.2
#> 15     8  2.26   58   M     not     57.2
#> 16     7  1.93   53   M     not     52.2
#> 17     5  1.47   50   M     not     52.2
#> 18     6  1.88   53   F     not     52.2
#> 19     9  2.35   59   M     not     63.2
#> 20     9  2.60   61.5 M     not     63.2
FEV |> head(20) |> mutate(group = ntiles(height, 3, format="interval"))
#> # A tibble: 20 × 6
#>      age   FEV height sex   smoker group    
#>    <int> <dbl>  <dbl> <chr> <chr>  <ord>    
#>  1     9  1.71   57   F     not    [56,58.5]
#>  2     8  1.72   67.5 F     not    [59,67.5]
#>  3     7  1.72   54.5 F     not    [50,54.5]
#>  4     9  1.56   53   M     not    [50,54.5]
#>  5     9  1.90   57   M     not    [56,58.5]
#>  6     8  2.34   61   F     not    [59,67.5]
#>  7     6  1.92   58   F     not    [56,58.5]
#>  8     6  1.42   56   F     not    [56,58.5]
#>  9     8  1.99   58.5 F     not    [56,58.5]
#> 10     9  1.94   60   F     not    [59,67.5]
#> 11     6  1.60   53   F     not    [50,54.5]
#> 12     8  1.74   54   M     not    [50,54.5]
#> 13     8  2.19   58.5 F     not    [56,58.5]
#> 14     8  2.12   60.5 M     not    [59,67.5]
#> 15     8  2.26   58   M     not    [56,58.5]
#> 16     7  1.93   53   M     not    [50,54.5]
#> 17     5  1.47   50   M     not    [50,54.5]
#> 18     6  1.88   53   F     not    [50,54.5]
#> 19     9  2.35   59   M     not    [59,67.5]
#> 20     9  2.60   61.5 M     not    [59,67.5]