R: Bins the values of a variable (typically a factor)

bin {fixest} | R Documentation

## Bins the values of a variable (typically a factor)

### Description

Tool to easily group the values of a given variable.

### Usage

    bin(x, bin)

### Arguments

`x` | A vector whose values have to be grouped. Can be of any type but must be atomic.
`bin` | A list of values to be grouped, a vector, or the special value `"bin::digit"`. To create a new value from old values, use `bin = list("new_value"=old_values)` with `old_values` a vector of existing values. It accepts regular expressions, but they must start with an `"@"`, like in `bin="@Aug|Dec"`. The names of the list are the new names. If the new name is missing, the first value matched becomes the new name. Feeding in a vector is like using a list without name and only a single element. If the vector is numeric, you can use the special value `"bin::digit"` to group every `digit` element. For example if `x` represent years, using `bin="bin::2"` create bins of two years. Using `"!bin::digit"` groups every digit consecutive values starting from the first value. Using `"!!bin::digit"` is the same bu starting from the last value. In both cases, `x` is not required to be numeric.

### Value

It returns a vector of the same length as `x`

### Examples

    data(airquality)
    month_num = airquality$Month
    table(month_num)

    # Grouping the first two values
    table(bin(month_num, 5:6))

    # ... plus changing the name to '10'
    table(bin(month_num, list("10" = 5:6)))

    # ... and grouping 7 to 9
    table(bin(month_num, list("g1" = 5:6, "g2" = 7:9)))

    # Grouping every two months
    table(bin(month_num, "bin::2"))

    # ... every 2 consecutive elements
    table(bin(month_num, "!bin::2"))

    # ... idem starting from the last one
    table(bin(month_num, "!!bin::2"))

    #
    # with non numeric data
    #

    month_lab = c("may", "june", "july", "august", "september")
    month_fact = factor(month_num, labels = month_lab)

    # Grouping the first two elements
    table(bin(month_fact, c("may", "jun")))

    # ... using regex
    table(bin(month_fact, "@may|jun"))

    # ...changing the name
    table(bin(month_fact, list("spring" = "@may|jun")))

    # Grouping every 2 consecutive months
    table(bin(month_fact, "!bin::2"))

    # ...idem but starting from the last
    table(bin(month_fact, "!!bin::2"))

[Package fixest version 0.10.0 Index]