R/recode_helper_data.R

Defines functions recode_helper_data

Documented in recode_helper_data

#' Recode Helper Data
#'
#' @param df The dataframe
#' @param column The column name to change
#' @param old_val The old value
#' @param new_val The new value
#'
#' @return A recoded dataframe.
#' @export
#'
#' @examples
recode_helper_data <- function(df, column, old_val, new_val) {

  df <- df %>% dplyr::mutate_at(
    dplyr::vars(column),
    dplyr::funs(as.character))

  if(!is.na(old_val)){

    if(new_val == "NA") {

      df <- df %>%
        dplyr::mutate_at(
          dplyr::vars(column),
          dplyr::funs(dplyr::case_when(. == old_val ~ NA_character_,
                            TRUE ~ .)))


    } else {

      df <- df %>%
        dplyr::mutate_at(
          dplyr::vars(column),
          dplyr::funs(dplyr::case_when(. == old_val ~ new_val,
                                TRUE ~ .)))
    }
  }

  cat("\014") #clears the console
  print(paste("The input ", new_val, " is replacing ", old_val, " for the variable: ", column))

  return(df)

}
SaeedR1987/healthyr documentation built on July 4, 2023, 11:17 p.m.