Chapter 12: R Numbers

R Numbers — basically everything you need to know about how R handles numeric values (numbers).

In R, “numbers” are not just one thing. There are two main kinds of numbers, plus special values like infinity or missing data. Understanding this deeply saves you from a lot of silent bugs later (especially with decimals, large datasets, or calculations).

I’m going to explain like your patient offline teacher — slow, with lots of real examples you can copy-paste right now into RStudio, why things behave this way, common mistakes, and 2026 best practices.

1. The Two Main Types of Numbers in R

R has two atomic numeric types:

Type Internal name (typeof()) What it is Default? Example creation Memory use When to use it intentionally
double “double” Floating-point real numbers (decimals) Yes 3.14, 1, c(28.5, 30.2) 8 bytes Almost always (default)
integer “integer” Whole numbers only No 42L, 1:10, as.integer(5) 4 bytes Big datasets, counts, indices

Key fact most beginners miss: Even when you write 5 or 100, R stores it as double (not integer)!

R

2. Why Two Types? (Practical Differences)

  • Double is the default → most math functions expect it
  • Integer saves memory (half the size) → useful for huge vectors (millions of rows)
  • Double allows decimals + special values (Inf, NaN)
  • Integer has only one special value: NA_integer_

Examples:

R

3. Creating Numbers – Hands-on Examples

R

4. Special Numeric Values (Very Important!)

Doubles have four special values — integers have only NA_integer_

Value Meaning How it appears Example how it happens
NA Missing / unknown value NA_real_ or NA_integer_ Data not collected, error in entry
NaN Not a Number (undefined math) NaN 0/0 , Inf – Inf , sqrt(-1)
Inf Positive infinity Inf 1/0 , exp(1000)
-Inf Negative infinity -Inf -1/0 , log(0)
R

5. Coercion / Automatic Conversion (The Silent Trap)

When you mix types in a vector, R coerces to the most flexible type:

logical < integer < double < complex < character

R

Very common bug:

R

Fix: Clean data first or use na_if() / lists / data frames for mixed types.

6. Precision & Comparison Warnings (Floating-Point Reality)

Doubles are approximations — never trust exact equality:

R

7. Your Mini Practice Right Now (Copy → Run!)

R

Summary Cheat-Sheet (Keep This!)

  • Most numbers → double (even 5 or 2026)
  • Want integer → add L or use as.integer()
  • Specials: NA (missing), NaN (undefined), Inf/-Inf
  • Coercion: doubles win over integers
  • Compare floats → use near() not ==
  • Always use na.rm = TRUE in summaries

Feeling good?

Next step?

  • Deeper into vectors (since numbers live in vectors)?
  • How numbers behave in data frames / dplyr?
  • Or any line confusing you right now?

Just tell me — whiteboard is ready! ☕🚀

You may also like...

Leave a Reply

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