recode_levels | R Documentation |
Recodes specified levels of a character/factor variable, e.g., to apply reverse coding before summary score computation.
recode_levels(data, vars, recode, temp = FALSE)
data |
tbl. Data frame containing the columns to be recoded. |
vars |
character (vector). The name(s) of the column(s) to be recoded. |
recode |
named character vector. The levels to be recoded, with the name being the original value and the value being the value to recode to. |
temp |
logical. If |
tbl. The input data frame with the recoded variable(s).
data <- tibble::tibble(
var_a = c("1", "2", "3", "4", "5", NA, "999", "777"),
var_b = c("5", "4", "3", "2", "1", "777", NA, "999")
)
# recode individual variables
data |>
recode_levels(
vars = "var_a",
recode = c("999" = "0", "777" = "0")
) |>
recode_levels(
vars = "var_b",
recode = c("999" = "6", "777" = "7")
)
# apply the same recoding to several variables
data |>
recode_levels(
vars = c(
"var_a",
"var_b"
),
recode = c(
"1" = "5",
"2" = "4",
"4" = "2",
"5" = "1"
)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.