Here are five ways to check data type in R:
- Using class(): For checking a single variable.
- Using str(): For checking the data type of every variable in a data frame.
- Using typeof(): For checking more basic data type of the object.
- Using is.* Functions: For checking specific data types.
- 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”.
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()
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.
Syntax
str(object)
Parameters
object: It takes the data frame object.
Example
df <- data.frame(a1 = 1:5, a2 = 6:10)
str(df)
Output
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:
- The “is.numeric()” checks if the variable is a numeric type.
- The “is.character()” checks if the variable is a character type.
- The “is.integer()” checks if the variable is an integer type.
- The “is.complex()” checks if the variable is a complex type.
- 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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.