jwutil (version 1.2.3)

two_cat_to_logical: Take dataframe, and convert any columns with just two categories into logical

Description

E.g. "Yes" would be converted to TRUE, "0" to FALSE, etc. If heuristics fail, then the function stops with an error message. NA values are counted, unless ignore_na is TRUE. When they are considered, na_val indicates whether they are attributed TRUE or FALSE.

Usage

two_cat_to_logical(x, ignore_na = FALSE, na_val = FALSE)

Arguments

x

input data frame

ignore_na

logical

na_val

Single value to use in place of NA``, default is FALSE`

Value

data frame with two categories columns replaced by logical columns

Examples

Run this code
# NOT RUN {
df <- data.frame(
  a = c("y", "n", "y", "y", "n"),
  b = c(FALSE, TRUE, FALSE, TRUE, TRUE),
  c = c(NA, NA, NA, NA, NA),
  d = c(NA, "yes", NA, NA, "yes"),
  e = c("y ", "n ", NA, "y ", "n "),
  f = c("YES   ", "NO     ", "NO    ", " YES", " NO "),
  stringsAsFactors = FALSE
)
df
res <- two_cat_to_logical(df)
stopifnot(identical(res$a, c(TRUE, FALSE, TRUE, TRUE, FALSE)))
stopifnot(identical(res$b, c(FALSE, TRUE, FALSE, TRUE, TRUE)))
two_cat_to_logical(df, ignore_na = TRUE)
# }

Run the code above in your browser using DataLab