class()

class(x)
Returns: character | NULL · Updated March 13, 2026 · Base Functions
oop class base object-oriented

The class() function in R is fundamental to the object’s class system. It retrieves or sets the class attribute of an object, which determines how generic functions dispatch methods.

Syntax

class(x)
class(x) <- value

Parameters

ParameterTypeDefaultDescription
xanyAn R object whose class to get or set

Examples

Getting the class of an object

# Vector class
x <- c(1, 2, 3)
class(x)
# [1] "numeric"

# Data frame class
df <- data.frame(a = 1:3, b = letters[1:3])
class(df)
# [1] "data.frame"

# Matrix class
m <- matrix(1:9, nrow = 3)
class(m)
# [1] "matrix" "array"

# Factor class
f <- factor(c("a", "b", "a"))
class(f)
# [1] "factor"

Checking class membership

# Use inherits() to check for class membership
x <- data.frame(a = 1)
inherits(x, "data.frame")
# [1] TRUE

# Check multiple classes
class(x)
# [1] "data.frame" "list"       "oldClass"

inherits(x, "list")
# [1] TRUE

Setting a class

# Create a custom class
x <- 1:10
class(x) <- "myVector"
class(x)
# [1] "myVector"

# Add class to existing object
y <- list(a = 1, b = 2)
class(y) <- "customList"
print.myList <- function(x) {
  cat("Custom list:\n")
  print(unclass(x))
}
print(y)

Common Patterns

S3 method dispatch

R uses the class to dispatch generic functions:

# The print generic looks at class
print

# It dispatches to print.data.frame for data.frames
print.data.frame <- function(x, ...) {
  # custom print behavior
}

# Same data, different class = different print
df <- data.frame(x = 1:3)
class(df) <- "myTable"
print(df)  # uses print.myTable if defined

Class inspection workflow

# Complete inspection of an object
obj <- mtcars

# 1. Get the class
class(obj)
# [1] "data.frame"

# 2. Get attributes
attributes(obj)

# 3. Check inheritance
inherits(obj, "data.frame")  # TRUE
inherits(obj, "matrix")       # FALSE

See Also