Labs ICT
โญ Pro Login

Data Types

Every value in R has a type โ€” a label that tells R what kind of data it's dealing with. Is it a number? A word? A true/false value? R needs to know so it can handle it correctly. Let's look at the five main data types you'll encounter.

Numeric (Double)

The default type for numbers in R is numeric, which means decimal numbers (also called doubles). When you write 42 or 3.14, R stores them as numeric by default. This covers most everyday numbers.


# Numeric values
price <- 19.99
price
class(price)
    
Try it Yourself โ†’

Integer

If you specifically want a whole number (no decimal part), add an L after it. This creates an integer type. Integers take less memory than doubles, which matters when you're working with huge datasets. But for everyday use, R's default numeric type works just fine.


# Integer values
count <- 100L
count
class(count)
    
Try it Yourself โ†’

Character (Strings)

Text in R is called character data, or strings. You create them by wrapping text in quotes โ€” either single or double quotes work. Characters are everywhere in data work: names, labels, categories, you name it.


# Character values
name <- "Alice"
fruit <- 'apple'
name
fruit
class(name)
    
Try it Yourself โ†’

Logical (Booleans)

Logical values are TRUE and FALSE. They come up whenever you ask a yes/no question: is this number bigger than that one? Does this row match a condition? R also accepts T and F as shortcuts.


# Logical values
is_sunny <- TRUE
is_raining <- FALSE
is_sunny
class(is_sunny)
    
Try it Yourself โ†’

Complex

Complex numbers are for mathematical computations involving imaginary numbers. You write them as 1 + 2i. You probably won't use these unless you're doing specific kinds of math or engineering, but it's good to know they exist.


# Complex values
z <- 3 + 4i
z
class(z)
    
Try it Yourself โ†’

The class() Function

Not sure what type something is? Use class(). It's R's way of telling you what kind of data you're looking at. When you're debugging or exploring unfamiliar data, class() is your first friend.


# Check any variable's type
x <- 42.5
y <- 42L
z <- "Hello"
class(x)
class(y)
class(z)
    
Try it Yourself โ†’

Knowing data types helps you avoid surprises. A number stored as text won't play nice with math, and a logical value won't multiply. Next up, let's dig deeper into how R handles numbers.

๐Ÿงช Quick Quiz

Which function tells you the data type of a variable?