Logical and Character Conversion
Convert between logical, character, and numeric with as.logical() and as.character().
Converting Between Types
R provides as.*() functions for converting between all basic types. This lesson covers conversions between logical, character, and numeric types — the most common round-trip conversions you will encounter in data cleaning.
# Quick overview of as.*() functions
cat('as.logical(1): ', as.logical(1), '
') # TRUE
cat('as.numeric(TRUE): ', as.numeric(TRUE), '
') # 1
cat('as.character(3.14):', as.character(3.14), '
') # "3.14"
cat('as.logical("TRUE"):', as.logical('TRUE'), '
') # TRUENumeric to Logical
Converting a number to logical: 0 becomes FALSE, any non-zero number becomes TRUE. This rule applies to both integers and doubles.
cat('as.logical(0): ', as.logical(0), '
') # FALSE
cat('as.logical(1): ', as.logical(1), '
') # TRUE
cat('as.logical(-5): ', as.logical(-5), '
') # TRUE (non-zero)
cat('as.logical(0.001):', as.logical(0.001), '
') # TRUE (non-zero)
cat('as.logical(0L): ', as.logical(0L), '
') # FALSE
cat('as.logical(3L): ', as.logical(3L), '
') # TRUEAll lessons in this course
- R's Type System Overview
- Converting Between Numeric Types
- Logical and Character Conversion
- Coercion Pitfalls and Best Practices