How to Check Data type of Variable in R

There are several useful functions in R that checks the variable type or convert between different variable types. For most of the major R objects, language provides is.datatype() function or as.datatype() function. For example, if we are checking for the vectors, then the R language provides is.vector() function to check if it is a vector or not and as.vector() function to coerce the different data types.

Objects are the instance of the class, and everything in R is an object. To know more about this, then take a look at Data types in R. These functions are R objects specific and not general, and there are functions through which you can find the data type of variables. Let’s find out the use cases of these functions.

Check data type in R

To check the data type of a variable in R, use the typeof() function. The typeof() is an inbuilt R function that determines the (internal) type or storage mode of any R object.

Syntax

typeof(x)

The is any R object.

Example

Define a vector of integers and see its data type using the typeof() function.

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

Output

[1] 11 15 18 19 21
[1] "double"

The internal data type of the above vector is numeric or double.

To check the numeric data type in R programming, use the is.numeric() function.

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

Output

[1] 11 15 18 19 21
[1] TRUE

And it returns TRUE that means the vector indeed contains the numeric components.

If the vector contains the character components, then it will return FALSE.

rv <- c("Check", "R", "Data type")
rv
is.numeric(rv)

Output

[1] "Check" "R" "Data type"
[1] FALSE

To check the specific character data type in R, use the is.character() method.

rv <- c("Check", "R", "Data type")
rv
is.character(rv)

Output

[1] "Check" "R" "Data type"
[1] TRUE

To check the data type of list in R, use the typeof( ) function.

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

Output

[1] "list"

Check data type in R using a class() function

To determine the class of any R object’s “internal” type, use the class() function. If the object does not have a class attribute, it has an implicit class, prominently “matrix“, “array“, “function” or “numeric” or the result of typeof(x). The class() function is robust.

Syntax

class(x)

The is an R Object.

Example

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

Output

[1] 11 15 18 19 21
[1] "numeric"

Conclusion

R language provides typeof() and class() function to check the variable’s data type, and if you want to check the specific data type, then R also provides those functions as well like is.numeric() or is.character(). They return either TRUE or FALSE value.

 

Leave a Comment