Learn R Programming

emil (version 2.2.3)

factor_to_logical: Convert factors to logicals

Description

Factors are converted to logical vectors or matrices depending on the number of levels. Ordered factors are converted to matrices where each column represent a level, coded TRUE for observations that match the level and FALSE otherwise. Unordered factors are converted in a similar way but coded TRUE for observations that match the level or a higher level. Interpred in words, the star rating example below returns a matrix containing a column named 3 stars that contains TRUE for observations with at least three stars and FALSE for observations with fewer than three stars.

Usage

factor_to_logical(x, base = 1L, drop = TRUE)

Arguments

Examples

Run this code
# Binary factor
email <- factor(sample(2, 20, TRUE), labels=c("unverified", "verified"))
factor_to_logical(email)

# Unordered multi-level factors
wine_preferences <- factor(sample(3, 20, TRUE),
                           labels=c("red", "white", "none"))
factor_to_logical(wine_preferences, base="none")

fruit <- factor(sample(4, 20, TRUE),
                labels = c("apple", "banana", "cantaloup", "durian"))
fruit[sample(length(fruit), 3)] <- NA
factor_to_logical(fruit, drop=FALSE)

# Ordered factor
rating <- factor(1:5, labels = paste(1:5, "stars"), ordered=TRUE)
factor_to_logical(rating)

# Ordered factor with custom base
tie_break <- factor(1:5,
                    labels=c("SetAlice", "AdvAlice", "Deuce", "AdvBob", "SetBob"),
                    ordered = TRUE)
tie_status <- as.data.frame(
    factor_to_logical(tie_break, base="Deuce", drop=FALSE)
)
print(tie_status)
tie_break[tie_status$AdvAlice]
tie_break[tie_status$SetBob]
tie_break[tie_status$Deuce]

Run the code above in your browser using DataLab