How to Check Data type in R

Here are five ways to check data type in R:

  1. Using class(): For checking a single variable.
  2. Using str(): For checking the data type of every variable in a data frame.
  3. Using typeof(): For checking more basic data type of the object.
  4. Using is.* Functions: For checking specific data types.
  5. Using mode() (not recommended): For checking information about how an object is stored in memory.

Method 1: Using class()

The class() function prints the vector of names of classes an object inherits from. If the object does not have a class attribute, it has an implicit class, prominently “matrix”, “array”, “function”, or “numeric”.

Visual Representation of Using a class() function

The above figure shows that we are dealing with a numeric vector.

Syntax

class(x)

Parameters

Name Description
x It is an R Object.

Example

rv <- c(11, 15, 18, 19, 21)
rv

class(rv)

Output

[1] 11 15 18 19 21

[1] "numeric"

Method 2: Using typeof()

Visual Representation of Using the typeof() function

In the above figure, we are checking the internal type of vector rv, which is double.

Syntax

typeof(x)

Parameters

x: It is any R object.

Example 1: Checking the data type of a vector

rv <- c(11, 15, 18, 19, 21)
typeof(rv)

rl <- list("Check", "R", "Data type")
typeof(rl)

Output

[1] "double"
[1] "list"

Method 3: Using str()

If you are working with a data frame, an easy way to check its data type is to use the “str()” function.

Visual Representation of Using the str() function

Syntax

str(object)

Parameters

object: It takes the data frame object.

Example

df <- data.frame(a1 = 1:5, a2 = 6:10)

str(df)

Output

Using the str() function

Method 4: Using is.* Functions

You can use the family of “is.*” functions (where the datatype could be a character, numeric, integer, complex, or logical). For example:

  1. The “is.numeric()” checks if the variable is a numeric type.
  2. The “is.character()” checks if the variable is a character type.
  3. The “is.integer()” checks if the variable is an integer type.
  4. The “is.complex()” checks if the variable is a complex type.
  5. The “is.logical()” checks if the variable holds a logical value, i.e., TRUE or FALSE.

These functions return a logical value (TRUE or FALSE) indicating whether the object is of the specified type.

main_data <- "hello"
num_data <- 22

is.numeric(main_data)
is.numeric(num_data)

Output

[1] FALSE
[1] TRUE

Method 5: Using mode()

data <- "r-lang.com"
mode(data)

num <- 22
mode(num)

bool <- FALSE
mode(bool)

Output

[1] "character"
[1] "numeric"
[1] "logical"

That’s it!

    Leave a Comment