R/mc_indicator.R

#' Multiple choice questions to dummy or indicator values.
#'
#' Multiple choice question options are in separate columns because the
#' respondent can select or not select any number of them, or several combinations.
#' @param column A vector containing the multiple choice answers.
#' @param selected What should be the replacement value of selected columns?
#' Defaults to \code{1}. In some cases this may vary from column to column.
#' @param unselected  Depending on your questionnaire, not selecting an answer option can have
#' different meanings. Mostly you should substitute unselected values with \code{0} but in some
#' cases \code{NA} may be a better option.
#' @param missing Are there explicit missings in your column. Defaults to \code{NA}.
#' @param na_id  Is there a special string for explicitly missing variables? (Default: \code{NA} )
#' @examples
#' mc_column_1 <- c("first option", NA, "first option", "NA" )
#'
#' mc_indicator ( column     = mc_column_1,
#'                selected   = 1,
#'                unselected = 0,
#'                missing    = 0,
#'                na_id      = NA)
#'
#' mc_indicator ( column     = mc_column_1,
#'                selected   = 1,
#'                unselected = 0,
#'                missing    = 0,
#'                na_id      = "NA")
#'
#' mc_column_2 <- c(NA, "second option", NA, "NA")
#'
#' mc_indicator ( column = mc_column_2,
#'                selected = 2,
#'                missing = NA,
#'                na_id = "NA")
#' @export


mc_indicator  <- function (column,
                           selected   = 1,
                           unselected = 0,
                           missing    = 0,
                           na_id      = NA) {

  column <- as.character(column)

  column <- ifelse ( is.na(column),
                     yes = as.character(missing),
                     no  = column )

  if ( !is.na(na_id)) {
    column <- ifelse ( column == na_id,
                       yes     = as.character(missing),
                       no      = column )
  }

  column <- ifelse ( column == as.character(unselected),
                     yes = unselected,
                     no  = selected )

  return(as.numeric(column))


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