get_dummies: Convert character and factor columns to dummy variables

View source: R/get_dummies.R

get_dummiesR Documentation

Convert character and factor columns to dummy variables

Description

Convert character and factor columns to dummy variables

Usage

get_dummies(
  .df,
  cols = where(~is.character(.x) | is.factor(.x)),
  prefix = TRUE,
  prefix_sep = "_",
  drop_first = FALSE,
  dummify_na = TRUE
)

Arguments

.df

A data.frame or data.table

cols

A single column or a vector of unquoted columns to dummify. Defaults to all character & factor columns using c(where(is.character), where(is.factor)). tidyselect compatible.

prefix

TRUE/FALSE - If TRUE, a prefix will be added to new column names

prefix_sep

Separator for new column names

drop_first

TRUE/FALSE - If TRUE, the first dummy column will be dropped

dummify_na

TRUE/FALSE - If TRUE, NAs will also get dummy columns

Examples

df <- tidytable(
  chr = c("a", "b", NA),
  fct = as.factor(c("a", NA, "c")),
  num = 1:3
)

# Automatically does all character/factor columns
df %>%
  get_dummies()

df %>%
  get_dummies(cols = chr)

df %>%
  get_dummies(cols = c(chr, fct), drop_first = TRUE)

df %>%
  get_dummies(prefix_sep = ".", dummify_na = FALSE)

tidytable documentation built on Sept. 11, 2024, 8:05 p.m.