R/better_worse_3.R

#' Better or worse scale
#'
#' Converts a standard better / same / worse scale to numeric 1, 0, -1.
#' @param column A column from a survey data frame where gender is recorded.
#' @param na_id  Is there a special character ID for missing variables? (Default: \code{"NA"} )
#' @param na_value  What should be the value of missing answers (Default: \code{"NA"}, but in some cases
#' it is useful to code them 0. )
#' If you get a warning with NA conversion, you are likely to have several NA characters,
#' such as \code{missing} and \code{NA} at the same time.
#' @param language Defaults to \code{"HU"} and \code{"EN"} is possible.
#' @importFrom stringr str_trim
#' @examples
#' better_worse_3 (column = c(
#'     "Jobb lesz", "Jobb lesz", "Ugyanolyan lesz",
#'     "Rosszabb lesz", "NA", "Rosszabb lesz"),
#'     language = "HU",
#'     na_id = "NA" )
#' @export

better_worse_3 <- function (column,
                          language = "HU",
                          na_id    = NA,
                          na_value = NA) {

  colun <- as.character (column)

  if (! is.na(na_id)) {
    n_na    <- nchar ( na_id )
    column <- ifelse ( substr(column, 1, n_na) == na_id,
                       yes = na_value, no = column ) #explict na replacement
  }

  supported_languages = c("HU", "EN")
  if (! language %in% supported_languages ) {
    stop("We have no scaling yet for this language.")
  }

  column <- tolower(column)
  if (language == "HU") {
   column <- ifelse (grepl("jobb", column), "1", column )
   column <- ifelse (grepl("rossz", column),  "-1", column)
   column <- ifelse (grepl("ugyanolyan", column), "0", column)
  }
  if (language == "EN") {
    column <- ifelse (grepl("better", column), "1", column )
    column <- ifelse (grepl("worse", column),  "-1", column)
    column <- ifelse (grepl("same", column), "0", column)
  }
  column <- ifelse (  column %in% c("1", "-1", "0"),
                      yes = column, no = NA)
  return(as.numeric(column))

}
antaldaniel/surveyreader documentation built on May 16, 2019, 2:29 a.m.