Learn R Programming

datawizard (version 0.8.0)

recode_into: Recode values from one or more variables into a new variable

Description

This functions recodes values from one or more variables into a new variable. It is a convenient function to avoid nested ifelse() statements, which is similar to dplyr::case_when().

Usage

recode_into(..., data = NULL, default = NA, verbose = TRUE)

Value

A vector with recoded values.

Arguments

...

A sequence of two-sided formulas, where the left hand side (LHS) is a logical matching condition that determines which values match this case. The LHS of this formula is also called "recode pattern" (e.g., in messages). The right hand side (RHS) indicates the replacement value.

data

Optional, name of a data frame. This can be used to avoid writing the data name multiple times in .... See 'Examples'.

default

Indicates the default value that is chosen when no match in the formulas in ... is found. If not provided, NA is used as default value.

verbose

Toggle warnings.

Examples

Run this code
x <- 1:30
recode_into(
  x > 15 ~ "a",
  x > 10 & x <= 15 ~ "b",
  default = "c"
)

set.seed(123)
d <- data.frame(
  x = sample(1:5, 30, TRUE),
  y = sample(letters[1:5], 30, TRUE),
  stringsAsFactors = FALSE
)

# from different variables into new vector
recode_into(
  d$x %in% 1:3 & d$y %in% c("a", "b") ~ 1,
  d$x > 3 ~ 2,
  default = 0
)

# no need to write name of data frame each time
recode_into(
  x %in% 1:3 & y %in% c("a", "b") ~ 1,
  x > 3 ~ 2,
  data = d,
  default = 0
)

Run the code above in your browser using DataLab