Learn R Programming

tidytable (version 0.8.0)

get_dummies.: Convert character and factor columns to dummy variables

Description

Convert character and factor columns to dummy variables

Usage

get_dummies.(
  .df,
  cols = c(where(is.character), where(is.factor)),
  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

Run this code
df <- tidytable(
  col1 = c("a", "b", "c", NA),
  col2 = as.factor(c("a", "b", NA, "d")),
  var1 = rnorm(4, 0, 1)
)

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

# Can select one column
df %>%
  get_dummies.(col1)

# Can select one or multiple columns in a vector of unquoted column names
df %>%
  get_dummies.(c(col1, col2))

# Can drop certain columns using
df %>%
  get_dummies.(c(where(is.character), -col2))

df %>%
  get_dummies.(prefix_sep = ".", drop_first = TRUE)

df %>%
  get_dummies.(c(col1, col2), dummify_na = FALSE)

Run the code above in your browser using DataLab