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
EasyCreate 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, yearThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values