Skip to contents

Counts the number of observations for a variable and calculates the corresponding percentages. Optionally converts the grouping variable to a factor using labels defined in the configuration object.

Usage

sum_up(dt, var, config, category = FALSE, digits = 1)

summarise(dt, var, config, category = FALSE, digits = 1)

summarize(dt, var, config, category = FALSE, digits = 1)

Arguments

dt

A data.table or data.frame. If a data.frame is supplied, it is converted internally to a data.table.

var

Variable to sum_up. Unquoted column name.

config

Configuration list containing value_map.

category

Logical. If TRUE, convert the grouping variable to a factor using labels from config$value_map.

digits

Number of decimal places used when rounding percentages.

Value

A data.table containing:

var

The grouping variable.

n

Number of observations.

pct

Percentage of observations.

Details

The function expects a configuration object containing a value_map element, where each variable name corresponds to a lookup table with columns num_value and chr_value.

If category = TRUE and the variable is of class haven_labelled, labels are extracted using haven::as_factor(levels = "labels").

Otherwise, labels are taken from config$value_map[[var_name]], using:

  • num_value as factor levels

  • chr_value as factor labels

Examples

library(data.table)
#> 
#> Attaching package: ‘data.table’
#> The following object is masked from ‘package:base’:
#> 
#>     %notin%

dt <- data.table(
  kjonn = c(1, 2, 1, 2, 1, 1, 2, 2, 1, 2)
)

cfg <- list(
  value_map = list(
    kjonn = data.table(
      num_value = c(1, 2),
      chr_value = c("Mann", "Kvinne")
    )
  )
)

sum_up(dt, kjonn, cfg)
#>    kjonn     n   pct
#>    <num> <int> <num>
#> 1:     1     5    50
#> 2:     2     5    50

sum_up(dt, kjonn, cfg, category = TRUE)
#>     kjonn     n   pct
#>    <fctr> <int> <num>
#> 1:   Mann     5    50
#> 2: Kvinne     5    50