0
0
R-programmingHow-ToBeginner · 3 min read

How to Use Class in R: Syntax, Example, and Tips

In R, you use class() to get or set the class attribute of an object, which defines its type and behavior. You can assign a class by using class(object) <- "classname" and check it with class(object).
📐

Syntax

The class() function in R is used to get or set the class of an object. When setting a class, you assign a character string representing the class name to the object.

  • Get class: class(object) returns the class name(s) of the object.
  • Set class: class(object) <- "classname" assigns a new class to the object.
r
class(object)          # Get the class of an object
class(object) <- "classname"  # Set the class of an object
💻

Example

This example shows how to create a simple object, assign a class to it, and then check its class.

r
x <- list(name = "Alice", age = 30)
class(x) <- "person"
print(class(x))

# You can also create a method for this class
print.person <- function(obj) {
  cat("Person:", obj$name, "is", obj$age, "years old.\n")
}

print(x)
Output
[1] "person" Person: Alice is 30 years old.
⚠️

Common Pitfalls

Common mistakes include:

  • Assigning class incorrectly by forgetting quotes around the class name.
  • Overwriting existing classes unintentionally.
  • Not defining methods for new classes, so default behavior is used.

Example of wrong and right way:

r
# Wrong: missing quotes
x <- 5
# class(x) <- person  # This causes an error

# Right:
class(x) <- "person"
print(class(x))
Output
[1] "person"
📊

Quick Reference

ActionSyntaxDescription
Get classclass(object)Returns the class name(s) of the object
Set classclass(object) <- "classname"Assigns a new class to the object
Check classinherits(object, "classname")Checks if object inherits from a class
Define methodprint.classname <- function(obj) { ... }Defines a method for objects of that class

Key Takeaways

Use class(object) to get the class of an object in R.
Assign a class with class(object) <- "classname" using quotes.
Defining methods for your class customizes object behavior.
Avoid missing quotes when setting class names to prevent errors.
Use inherits(object, "classname") to check class membership.