Learn R Programming

jwutil (version 1.2.3)

factor_to_df: Convert factor into a data.frame of logicals

Description

Convert a single factor into a data.frame with multiple true or false fields, one for each factor. The `vtreat` package may be a better choice for more comprehensive data preparation.

Usage

factor_to_df(fctr, prefix = deparse(substitute(fctr)), sep = "",
  drop_empty = TRUE, na_as_col = TRUE, verbose = FALSE)

factorToDataframeLogical(fctr, prefix = deparse(substitute(fctr)), sep = "", drop_empty = TRUE, na_as_col = TRUE, verbose = FALSE)

Arguments

fctr

factor

prefix

defaults to "f" to pre-pend the factor level when constructing the data frame columns names

sep

scalar character, introduced between factor names and levels when forming new data frame column names

drop_empty

logical, if `TRUE` (the default) factor levels with no associated values are dropped.

na_as_col

logical scalar: if NA data and/or NA levels, then covert to NA strings and expand these as for any other factor

verbose

single logical value, if TRUE then produce verbose messages

Value

data.frame with columns of logicals

Examples

Run this code
# NOT RUN {
n <- 10
m <- 20
l <- LETTERS[seq_len(n)]
set.seed(1441)
f <- factor(sample(l, m, replace = TRUE), levels = l)
g <- factor_to_df(f, drop_empty = FALSE)
print(g)
stopifnot(nrow(g) == m, ncol(g) == n)
factor_to_df(
  shuffle(factor(shuffle(LETTERS[1:10]))),
  prefix = ""
)
factor_to_df(factor(c(NA, 1, 2, 3)))
factor_to_df(factor(c(NA, 1, 2, 3)), na_as_col = FALSE)
# }

Run the code above in your browser using DataLab