R Tutorial



R TYPE CHECKING


Type Checking in R

In R, it's important to check the type of variables to understand how data is stored and how it behaves. R provides several functions to test the type or class of a variable.

Common Type Checking Functions

  • class(x) – Returns the class/type of object x.
  • typeof(x) – Returns the internal storage mode of x.
  • is.numeric(x) – Checks if x is numeric.
  • is.integer(x) – Checks if x is an integer.
  • is.character(x) – Checks if x is a character string.
  • is.logical(x) – Checks if x is logical (TRUE/FALSE).

Example: Type Checking

a <- 10
b <- 10L
c <- "R language"
d <- TRUE

print(class(a))          # "numeric"
print(typeof(a))         # "double"
print(is.numeric(a))     # TRUE
print(is.integer(a))     # FALSE

print(class(b))          # "integer"
print(is.integer(b))     # TRUE

print(class(c))          # "character"
print(is.character(c))   # TRUE

print(class(d))          # "logical"
print(is.logical(d))     # TRUE
  

Why Type Checking Matters

Type checking helps avoid errors by ensuring functions receive the expected data types. It’s also useful when debugging and for conditional programming based on data types.

πŸ’‘ Quick Tip:

Use class() for general type info, but typeof() gives the underlying storage type. Use specific is.*() functions for clear boolean checks.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review