Learn R Programming

sparsevctrs (version 0.3.1)

sparse_dummy: Generate sparse dummy variables

Description

Generate sparse dummy variables

Usage

sparse_dummy(x, one_hot = TRUE)

Value

A list of sparse integer dummy variables.

Arguments

x

A factor.

one_hot

A single logical value. Should the first factor level be included or not. Defaults to FALSE.

Details

Only factor variables can be used with sparse_dummy(). A call to as.factor() would be required for any other type of data.

If only a single level is present after one_hot takes effect. Then the vector produced won't be sparse.

A missing value at the ith element will produce missing values for all dummy variables at thr ith position.

Examples

Run this code
x <- factor(c("a", "a", "b", "c", "d", "b"))

sparse_dummy(x, one_hot = FALSE)

x <- factor(c("a", "a", "b", "c", "d", "b"))

sparse_dummy(x, one_hot = TRUE)

x <- factor(c("a", NA, "b", "c", "d", NA))

sparse_dummy(x, one_hot = FALSE)

x <- factor(c("a", NA, "b", "c", "d", NA))

sparse_dummy(x, one_hot = TRUE)

Run the code above in your browser using DataLab