Select Page


In the world of R programming, the class() function is a versatile tool that plays a crucial role in object-oriented programming. Understanding how to use the class() function effectively can enhance your ability to manipulate and analyze data, ultimately improving your R programming skills. In this blog post, we will dive deep into the class() function, exploring its features and providing code examples to help you grasp its full potential.

What is the class() Function?

The class() function in R is used to determine or set the class of an object. The class of an object defines its data type and behavior within the R environment. By using the class() function, you can identify the class of an object or assign a new class to an object.

Checking the Class of an Object

To check the class of an object, you can simply pass the object as an argument to the class() function. Let’s consider an example using a numeric vector:

# Create a numeric vector
my_vector <- c(1, 2, 3, 4, 5)

# Check the class of my_vector
#[1] "numeric"

In this example, we created a numeric vector called my_vector and used the class() function to determine its class, which is “numeric.”

Assigning a New Class to an Object

In addition to checking the class, you can also use the class() function to assign a new class to an object. This can be useful when working with custom-defined classes or when you want to redefine the behavior of an object. Let’s see how this works with a simple example:

# Create a character vector
my_vector <- c("apple", "banana", "cherry")

# Assign the class "fruits" to my_vector
class(my_vector) <- "fruits"

# Check the new class of my_vector

#[1] "fruits"

Here, we created a character vector called my_vector and assigned it the class “fruits” using the class() function. By redefining the class, we can now treat my_vector as a specialized object.


The class() function in R is a powerful tool for understanding and manipulating objects. Whether you want to determine the class of an object or assign a new class, the class() function enables you to work with different data types and customize their behavior. By mastering the usage of this function, you can unlock advanced programming techniques and leverage the full potential of object-oriented programming in R.

Remember to experiment with different classes and explore how they affect the behavior of objects. The class() function opens up endless possibilities for creating efficient and well-structured code in R.

Happy coding!