Menu
Coddy logo textTech

Checking Data Types

Part of the Fundamentals section of Coddy's R journey — lesson 8 of 78.

R provides the class() function to check the data type.

The class() function takes a variable as input and returns a character string telling you the data type. Simply pass your variable name inside the parentheses:

my_variable <- 42
class(my_variable)

This will return "numeric" because the variable contains a numeric value. Similarly, class() will return "character" for text data, "logical" for TRUE/FALSE values, and "integer" for integer data types.

You can combine class() with print() to display the data type to the console, making it easy to verify what kind of data you're working with at any point in your program.

challenge icon

Challenge

Easy

Create four different variables with different data types, then use the class() function to check and display the data type of each variable.

First, create a variable called score and assign it the value 88.5. Then create a variable called student_name and assign it the value "Sarah". Next, create a variable called passed and assign it the value TRUE. Finally, create a variable called year and assign it the value 2024L.

After creating all four variables, use the class() function combined with print() to display the data type of each variable in this exact order: score, student_name, passed, and year.

Cheat sheet

Use the class() function to check the data type of a variable:

my_variable <- 42
class(my_variable)

The class() function returns:

  • "numeric" for numeric values
  • "character" for text data
  • "logical" for TRUE/FALSE values
  • "integer" for integer data types

Combine class() with print() to display the data type:

print(class(my_variable))

Try it yourself

# TODO: Create four variables with the specified values and data types

# TODO: Use class() function with print() to display the data type of each variable
# Remember to display them in this order: score, student_name, passed, year
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals