R Type Conversion

Type conversion means changing data from one type to another. R can convert between numeric, integer, character, logical, and complex types. This happens in two ways: explicitly (you tell R to convert) and implicitly (R converts automatically when needed).

Why Type Conversion Matters

Real-world datasets rarely arrive in perfect condition. A CSV file might store ages as text ("30", "25") instead of numbers, or store TRUE/FALSE values as 1/0. Before analyzing such data, you convert it to the correct type.

Raw Data (from CSV)         After Conversion
──────────────────────      ─────────────────────────────
age = "28"                  age = 28   (numeric)
score = "85.5"              score = 85.5 (numeric)
active = "1"                active = TRUE (logical)
category = 3                category = "Product C" (character)

Explicit Conversion Functions

Function          Converts To     Example
───────────────────────────────────────────────────────────
as.numeric(x)     numeric         as.numeric("3.14") → 3.14
as.integer(x)     integer         as.integer(7.9) → 7
as.character(x)   character       as.character(100) → "100"
as.logical(x)     logical         as.logical(0) → FALSE
as.complex(x)     complex         as.complex(5) → 5+0i

Conversion Hierarchy

Type Hierarchy (most to least flexible):
──────────────────────────────────────────────────────
complex > numeric > integer > logical > character

Rule: R always converts to the "higher" type in mixed situations

This means if you combine a logical and a numeric value in a vector, R automatically converts the logical to numeric. If you mix numeric and character, everything becomes character.

Implicit (Automatic) Conversion

# Logical → Numeric (automatic in math)
TRUE + 5     # 6  (TRUE becomes 1)
FALSE * 10   # 0  (FALSE becomes 0)

# Mixing logical and numeric in a vector
c(TRUE, FALSE, 5, 3)
# [1] 1 0 5 3  (all become numeric)

# Mixing numeric and character in a vector
c(10, 20, "hello")
# [1] "10" "20" "hello"  (all become character)

Conversion Success vs Failure

Not all conversions succeed. When R cannot convert a value, it produces NA (Not Available) with a warning.

as.numeric("123")    # 123       — success
as.numeric("abc")    # NA        — warning: NAs introduced
as.integer("7.5")    # 7         — success (truncates decimal)
as.logical("yes")    # NA        — "yes" is not recognized
as.logical("TRUE")   # TRUE      — "TRUE" string works
as.logical(1)        # TRUE      — 1 → TRUE
as.logical(0)        # FALSE     — 0 → FALSE
as.logical(5)        # NA        — only 0 and 1 convert to logical

Checking Types Before Converting

Always check the current type before converting:

x <- "42"
class(x)          # "character"
is.numeric(x)     # FALSE

x <- as.numeric(x)
class(x)          # "numeric"
is.numeric(x)     # TRUE

Practical Example: Cleaning Survey Data

# Raw survey responses (all read as character from CSV)
age_raw      <- "34"
income_raw   <- "75000.50"
employed_raw <- "1"
city_raw     <- "Bengaluru"

# Convert to correct types
age      <- as.integer(age_raw)
income   <- as.numeric(income_raw)
employed <- as.logical(as.integer(employed_raw))
city     <- city_raw    # already character, no conversion needed

cat("Age:", age, class(age), "\n")
cat("Income:", income, class(income), "\n")
cat("Employed:", employed, class(employed), "\n")

Output:

Age: 34 integer
Income: 75000.5 numeric
Employed: TRUE logical

Conversion Flow Diagram

      character
          │
          │  as.numeric("3.14")
          ▼
        numeric ◄──── complex
          │
          │  as.integer(3.14)
          ▼
        integer
          │
          │  as.logical(1)
          ▼
        logical

Safe Conversion Pattern

When converting data you do not fully trust, check for NAs after converting:

raw_values <- c("10", "20", "abc", "30")
converted  <- as.numeric(raw_values)

print(converted)
# [1] 10 20 NA 30

# Count how many failed to convert
sum(is.na(converted))
# [1] 1

This pattern catches bad data early, before it causes incorrect analysis results downstream. Type conversion is one of the most common data cleaning tasks you will perform in every real R project.

Leave a Comment

Your email address will not be published. Required fields are marked *