mutate_ntile: Add a column of ntiles to a data table

View source: R/mutate_ntile.R

mutate_ntileR Documentation

Add a column of ntiles to a data table

Description

Add a column of ntiles to a data table

Usage

mutate_ntile(
  DT,
  col,
  n,
  weights = NULL,
  by = NULL,
  keyby = NULL,
  new.col = NULL,
  character.only = FALSE,
  overwrite = TRUE,
  check.na = FALSE
)

Arguments

DT

A data.table.

col

The column name (quoted or unquoted) for which quantiles are desired.

n

A positive integer, the number of groups to split col.

weights

If NULL, the default, use unweighted quantiles. Otherwise, a string designating the column that is passed to weighted_ntile.

by, keyby

Produce a grouped quantile column, as in data.table. keyby will set a key on the result (i.e. order by keyby).

new.col

If not NULL, the name of the column to be added. If NULL (the default) a name will be inferred from n. (For example, n = 100 will be <col>Percentile).

character.only

(logical, default: FALSE) Do not contemplate col to be an unquoted column name.

overwrite

(logical, default: TRUE) If TRUE and new.col already exists in DT, the column will be overwritten. If FALSE, attempting to overwrite an existing column is an error.

check.na

(logical, default: FALSE) If TRUE, NAs in DT[[col]] will throw an error. If NA's are present, the corresponding n-tile may take any value.

Value

DT with a new integer column new.col containing the quantiles. If DT is not a data.table its class may be preserved unless keyby is used, where it will always be a data.table.

Examples

library(data.table)
DT <- data.table(x = 1:20, y = 2:1)
mutate_ntile(DT, "x", n = 10)
mutate_ntile(DT, "x", n = 5)
mutate_ntile(DT, "x", n = 10, by = "y")
mutate_ntile(DT, "x", n = 10, keyby = "y")

y <- "x"
DT <- data.table(x = 1:20, y = 2:1)
mutate_ntile(DT, y, n = 5)                        # Use DT$y
mutate_ntile(DT, y, n = 5, character.only = TRUE) # Use DT$x


hutils documentation built on April 13, 2022, 5:23 p.m.