Home » How to Check Data Type in R (With Examples)

How to Check Data Type in R (With Examples)

by Tutor Aspire

You can use the following functions to check the data type of variables in R:

#check data type of one variable
class(x)

#check data type of every variable in data frame
str(df)

#check if a variable is a specific data type
is.factor(x)
is.numeric(x)
is.logical(x)

The following examples show how to use these functions in practice.

Example 1: Check Data Type of One Variable

The following code shows how to check the data type of one variable in R:

#define variable x
x Andy", "Bob", "Chad", "Dave", "Eric", "Frank")

#check data type of x
class(x)

[1] "character"

We can see that x is a character variable.

Example 2: Check Data Type of Every Variable in Data Frame

The following code shows how to check the data type of every variable in a data frame:

#create data frame
df frame(x=c(1, 3, 4, 4, 6),
                 y=c("A", "B", "C", "D", "E"),
                 z=c(TRUE, TRUE, FALSE, TRUE, FALSE))

#view data frame
df

  x y     z
1 1 A  TRUE
2 3 B  TRUE
3 4 C FALSE
4 4 D  TRUE
5 6 E FALSE

#find data type of every variable in data frame
str(df)

'data.frame':	5 obs. of  3 variables:
 $ x: num  1 3 4 4 6
 $ y: chr  "A" "B" "C" "D" ...
 $ z: logi  TRUE TRUE FALSE TRUE FALSE

From the output we can see:

  • Variable x is a numeric variable.
  • Variable y is a character variable.
  • Variably z is a logical variable.

Example 3: Check if Variable is Specific Data Type

The following code shows how to check the if a specific variable in a data frame is a numeric variable:

#create data frame
df frame(x=c(1, 3, 4, 4, 6),
                 y=c("A", "B", "C", "D", "E"),
                 z=c(TRUE, TRUE, FALSE, TRUE, FALSE))

#check if x column is numeric
is.numeric(df$x)

[1] TRUE

Since the output returned TRUE, this indicates that the x column in the data frame is numeric.

We can also use the sapply() function to check if every column in the data frame is numeric:

#check if every column in data frame is numeric
sapply(df, is.numeric)

    x     y     z 
 TRUE FALSE FALSE 

We can see that column x is numeric, while columns y and z are not.

Additional Resources

How to Convert Factor to Character in R
How to Convert Character to Numeric in R
How to Convert Numbers to Dates in R
How to Convert Strings to Dates in R

You may also like