0Pricing
R Academy · Lesson

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'), '
') # TRUE

Numeric 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), '
')    # TRUE

All lessons in this course

  1. R's Type System Overview
  2. Converting Between Numeric Types
  3. Logical and Character Conversion
  4. Coercion Pitfalls and Best Practices
← Back to R Academy