Skip to contents

as_logical() enhances as.logical(), especially when input is a character, by treating some comon cases, at least in English and French context.

Usage

to_logical(x, true, false, as_is = FALSE)

Arguments

x

vector, values to be transformed.

true

character, optional values for TRUE cases.

false

character, optional values for FALSE cases.

as_is

logical, should result be sent as character (for recursive call).

Value

logical

Details

When applied to a character vector, as_logical() tests if all values are in a set of admissibles values for TRUE cases, FALSE cases, and NA cases. If it is the case, it makes all substitutions so that a logical vector is returned by as.logical().

Some defaults cases are implemented (all insensitive to case)

  • English TRUE/FALSE with:

    • TRUE for "T" and "TRUE"

    • FALSE for "F" and "FALSE"

  • English YES/NO with:

    • TRUE for "Y" and "YES"

    • FALSE for "N" and "NO"

  • French TRUE/FALSE with:

    • TRUE for "V" and "VRAI"

    • FALSE for "F" and "FAUX"

  • French YES/NO with:

    • TRUE for "O" and "OUI"

    • FALSE for "N" and "NON"

true and false can be used to add more cases. To be used they must be both given, if not none is considered. Even if true and false are given, default substitutions for French and English cases are performed.

Examples


# Default behaviour
to_logical(c(0:2, NA))
#> [1] FALSE  TRUE  TRUE    NA

# For English (default, case insensitive)
to_logical(c("true", "false", "t", "f", "True", "False", "", "NA", NA))
#> [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE    NA    NA    NA
to_logical(c("y", "n", "Yes", "No"))
#> [1]  TRUE FALSE  TRUE FALSE

# For French (default)
to_logical(c("n", "o", "Non", "Oui"))
#> [1] FALSE  TRUE FALSE  TRUE
to_logical(c("v", "f", "vrai", "faux"))
#> [1]  TRUE FALSE  TRUE FALSE

# For other convention (language)
x = c("si", "no", NA)
to_logical(x)
#> [1] NA NA NA
to_logical(x, true = "SI", false = "NO")
#> [1]  TRUE FALSE    NA

# Cannot mix language (by default)
x = c("NON", "OUI", "YES", "NO")
to_logical(x)
#> [1] NA NA NA NA

# Can use parameters in this case
to_logical(x, true = c("OUI", "YES"), false = c("NO", "NON"))
#> [1] FALSE  TRUE  TRUE FALSE