#' Scale factor
#'
#' Converts factors that are scaled, only in the case where the scaling is
#' coded with starting numbers such as "3 - city", "2 - town", "1 - village".
#' @param column A column from a survey data frame where gender is recorded.
#' @param digits How many digits are valid in the scaling.
#' @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 is_integer Numeric or integer should be returned? Defaults to \code{FALSE} in which case no validation takes place.
#' @importFrom stringr str_trim
#' @examples
#' scale_factor (column = as.character (c("3 - city",
#' "2 - town", NA, "NA", "1 - village")),
#' digits = 1,
#' na_id = "NA",
#' is_integer = FALSE )
#' @export
scale_factor <- function (column,
digits = 1,
na_id = NA,
na_value = NA,
is_integer = FALSE) {
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
}
column <- substr(column, 1, digits)
column <- stringr::str_trim(column, side = "both")
if ( is_integer == TRUE) {
return(as.integer(column))
}
return(as.numeric(column))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.