Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

R Classes and Objects


Share

Classes and Objects

In R, everything you work with is an object: a number, a string, a vector, a list, a data frame, and even a function.

Every object has a class. The class tells R what kind of object it is, and how to work with it.

You have already used the class() function to find the class of an object:

Example

x <- 10
y <- "Hello"
z <- TRUE

class(x)
class(y)
class(z)
Try it Yourself »

What is a Class?

A class is like a template for objects, and an object is one thing made from that template.

For example, "Fruit" can be a class, and Apple, Banana and Mango are objects of that class. They are all fruits, but each one has its own name, color and taste.

Class Objects
FruitApple, Banana, Mango
CarVolvo, Audi, Toyota

Why Classes Matter

Some R functions look at the class of an object, and do what fits that class.

For example, summary() shows statistics for numbers, but counts for a factor:

Example

numbers <- c(10, 20, 30, 40)
summary(numbers)

colors <- factor(c("red", "blue", "red"))
summary(colors)
Try it Yourself »

A function like summary() or print(), which works differently for each class, is called a generic function.



Create Your Own Classes

You can also create your own classes, for example a class for players in a game, with a name and points.

R has two main systems for this:

System Description
S3Simple and flexible. Most of R's own classes, like data frames and factors, use S3.
S4More formal and strict. You must describe the class first, and R checks the type of every value.

You will learn both in the next chapters.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.