How to Use typeof in R: Syntax and Examples
In R, use the
typeof() function to find the internal type of any object. Simply pass the object as an argument like typeof(object), and it returns a string describing the object's type.Syntax
The typeof() function takes one argument, which is the object you want to check. It returns a string that describes the internal type of that object.
typeof(x): Returns the type ofx.
r
typeof(x)
Example
This example shows how to use typeof() on different kinds of objects like numbers, characters, and logical values.
r
num <- 42 char <- "hello" logic <- TRUE typeof(num) typeof(char) typeof(logic)
Output
[1] "double"
[1] "character"
[1] "logical"
Common Pitfalls
People often confuse typeof() with class(). typeof() shows the low-level type, while class() shows the object's class used for method dispatch. Also, typeof() does not tell you if a number is integer or double unless you explicitly create an integer.
Example of confusion:
r
# Wrong: expecting typeof to show 'integer' x <- 5 typeof(x) # returns 'double' because 5 is numeric by default # Right: create integer explicitly x_int <- 5L typeof(x_int) # returns 'integer'
Output
[1] "double"
[1] "integer"
Quick Reference
| Type | Description |
|---|---|
| "logical" | TRUE or FALSE values |
| "integer" | Whole numbers with L suffix, e.g., 5L |
| "double" | Decimal numbers (default numeric type) |
| "character" | Text strings |
| "complex" | Complex numbers with real and imaginary parts |
| "raw" | Raw bytes |
| "list" | List of elements |
| "NULL" | Empty or null object |
Key Takeaways
Use typeof(object) to get the internal type of any R object.
typeof() returns low-level types like 'double', 'integer', or 'character'.
Numeric values are 'double' by default unless marked with L for integer.
typeof() differs from class(), which shows the object's class.
Check typeof() when you need to understand the exact storage type.