% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{recode_levels}
\alias{recode_levels}
\title{Recode levels}
\usage{
recode_levels(data, vars, recode, temp = FALSE)
}
\arguments{
\item{data}{tbl. Data frame containing the columns to be recoded.}

\item{vars}{character (vector). The name(s) of the column(s) to be recoded.}

\item{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.}

\item{temp}{logical. If \code{TRUE} creates a new column to save the recoded
values. The new columns will be named as \verb{temp_\{vars\}}.}
}
\value{
tbl. The input data frame with the recoded variable(s).
}
\description{
Recodes specified levels of a character/factor variable, e.g., to apply
reverse coding before summary score computation.
}
\examples{
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"
    )
  )
}
