R/rescale_direction.R

#' Rescale direction trend question
#'
#' Create a uniform variable from the three categories such as
#' \code{"Things are going in the right direction"},
#' \code{"Things are going in the wrong direction"},
#' \code{"Neither one nor the other (SPONTANEOUS)"} or
 #' \code{" In the right direction"},
#' \code{"In the wrong direction"},
#' \code{"Neither one nor the other (SPONTANEOUS)"}.
#' This is a wrapper function around the \code{\link{rescale_categories}} function.
#' @param column A column from a survey data frame where gender is recorded.
#' @param from Defaults to \code{c("right direction", "wrong direction",
#' "neither one nor the other")} and looks for partial match in the text.
#' Most other  \code{\link{rescale_categories}} functions are looking for
#' exact but non-case sensitive matches.
#' @param to Defaults to \code{c(1,-1,0)}. If  \code{return_class = "character"} or
#' \code{return_class = "factor"} is selected it returns the abbreviated category
#' names \code{c("right", "wrong", "neither")}.
#' @param na_labels  Defaults to \code{c("DK")}.
#' @param exact_from Deafults to \code{TRUE}. If \code{FALSE} you can use the
#' partial matching, but beware that in this case, \code{"twenty"} will be replaced by
#' @param return_class Default is \code{"numeric"}, alternatives \code{"character"} or
#' \code{"factor"}.
#' @examples
#' rescale_direction  (
#' column = c("In the right direction",
#'            "Things are going in the wrong direction",
#'            "In the wrong direction",
#'            "Thins are going in the right direction",
#'            "Neither the one or the other (SPONTANEOUS)",
#'            "Inap. (not 1 in eu28)", "DK"))
#'
#' @export

rescale_direction <- function ( column,
                                 from = c("right direction",
                                          "wrong direction",
                                          "neither"),
                                 to = c(1,-1,0),
                                 na_labels = "default",
                                 exact_from = TRUE,
                                 return_class = "numeric") {
  if ( return_class %in% c("character", "factor")) {
    to = c("right", "wrong", "neither")
  }
  if ( "labelled" %in% class(column)  ) {
    column <- haven::as_factor (column) }

  #"In the right direction"
  column <- tolower(as.character(column))
  column <- ifelse ( grepl("right direction", column), "right direction", column )
  column <- ifelse ( grepl("wrong direction", column), "wrong direction", column )
  column <- ifelse ( grepl("neither", column),
                     "neither", column )

  return(rescale_categories(column = column,
                            from = from, to = to,
                            na_labels = na_labels,
                            exact_from = TRUE,
                            return_class = return_class))

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