Home / Programs / What's that data type in R?
Programming Example

What's that data type in R?

👁 406 Views
💻 Practical Program
📘 Step by Step Learning

Do you remember that when you added 5 + "six", you got an error due to a mismatch in data types? You can avoid such embarrassing situations by checking the data type of a variable beforehand. You can do this with the class() function, as the code on the right shows.

Program Code

# Declare variables of different types
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE 

# Check class of my_numeric
class(my_numeric)

# Check class of my_character
class(my_character)

# Check class of my_logical
class(my_logical)

 

Output

> # Declare variables of different types
> my_numeric <- 42
> my_character <- "universe"
> my_logical <- FALSE
> 
> # Check class of my_numeric
> class(my_numeric)
[1] "numeric"
> 
> # Check class of my_character
> class(my_character)
[1] "character"
> 
> # Check class of my_logical
> class(my_logical)
[1] "logical"

Explanation

Complete the code in the editor and also print out the classes of my_character and my_logical.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.