3. Classes - JulTob/R GitHub Wiki

🧭 Compass of Basic Classes

“Know the shape of yer cargo, or risk a capsized script!”

In R, every object has a class—a kind of invisible label tellin’ R what that object is, and what it can do. The most common ones—the usual suspects—are:

1️⃣ Numeric — The Number Runner

my_numeric <- 42
class(my_numeric)
[1] "numeric"
  • Holds decimal or integer values.
  • Used in calculations, models, charts, and more.

If ye want to make a true integer, use L:

my_integer <- 7L
class(my_integer)
[1] "integer"

⚓ Technically, both numeric and integer are number-types, but they be distinct classes!

2️⃣ Character — The String-Slinger

my_character <- "universe"
class(my_character)
[1] "character"
  • Holds letters, words, phrases—quoted like treasure maps.
  • R treats it as text, not math.

Ye can glue strings together with paste() or glue() (from the tidyverse).

3️⃣ Logical — The Truth-Teller

my_logical <- FALSE
class(my_logical)
[1] "logical"
  • Either TRUE or FALSE (in ALL CAPS, like a good sailor shouts).
  • Often born from comparisons:
is_equal <- 1 == 1
class(is_equal)
[1] "logical"

These logicals be the compass rose of R, guiding filters, if-statements, and pirates’ choices.

🪝 Why Check Class?

Knowing the class of your variable helps ye:

  • Understand how functions will treat it.
  • Avoid silent type conversions (e.g., "5" + 2 → error!)
  • Write clearer, bug-proof code.

⛵ Bonus Tip: Test the Class

is.numeric(3.14)     # TRUE
is.character("yar")  # TRUE
is.logical(FALSE)    # TRUE

Now you’ve met the core crew—numeric, character, and logical. Later voyages will uncover more exotic classes: factors, lists, data.frames, and the kraken known as the function.