recode_into | R Documentation |
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()
.
recode_into(
...,
data = NULL,
default = NA,
overwrite = TRUE,
preserve_na = FALSE,
verbose = TRUE
)
... |
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 |
default |
Indicates the default value that is chosen when no match in
the formulas in |
overwrite |
Logical, if |
preserve_na |
Logical, if |
verbose |
Toggle warnings. |
A vector with recoded values.
x <- 1:30
recode_into(
x > 15 ~ "a",
x > 10 & x <= 15 ~ "b",
default = "c"
)
x <- 1:10
# default behaviour: second recode pattern "x > 5" overwrites
# some of the formerly recoded cases from pattern "x >= 3 & x <= 7"
recode_into(
x >= 3 & x <= 7 ~ 1,
x > 5 ~ 2,
default = 0,
verbose = FALSE
)
# setting "overwrite = FALSE" will not alter formerly recoded cases
recode_into(
x >= 3 & x <= 7 ~ 1,
x > 5 ~ 2,
default = 0,
overwrite = FALSE,
verbose = FALSE
)
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
)
# handling of missing values
d <- data.frame(
x = c(1, NA, 2, NA, 3, 4),
y = c(1, 11, 3, NA, 5, 6)
)
# first NA in x is overwritten by valid value from y
# we have no known value for second NA in x and y,
# thus we get one NA in the result
recode_into(
x <= 3 ~ 1,
y > 5 ~ 2,
data = d,
default = 0,
preserve_na = TRUE
)
# first NA in x is overwritten by valid value from y
# default value is used for second NA
recode_into(
x <= 3 ~ 1,
y > 5 ~ 2,
data = d,
default = 0,
preserve_na = FALSE
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.