R Programming language - R Objects and Classes

www.igift‮i‬dea.com

In R programming language, everything is an object. An object is a data structure that contains data and functions that can operate on that data. R has a variety of built-in classes for objects, and you can also define your own custom classes.

Here are some examples of R's built-in classes:

  • numeric - used for numerical values, including integers and floating-point numbers.
  • character - used for character strings.
  • logical - used for Boolean values (TRUE and FALSE).
  • factor - used for categorical variables.
  • list - used for a collection of objects of any class.
  • data.frame - used for tabular data.

Each object in R has a class attribute that specifies its class. You can use the class() function to get the class of an object, like this:

x <- 1:10
class(x)

This will output "integer", indicating that x is an object of the integer class.

R also supports object-oriented programming (OOP) through the use of classes and methods. You can define your own classes and methods using the setClass() and setMethod() functions, respectively.

Here is an example of defining a custom class in R:

setClass("myclass", slots = list(x = "numeric", y = "character"))

In this example, we define a new class called myclass with two slots (x and y) of different classes (numeric and character). You can create an object of this class using the new() function, like this:

obj <- new("myclass", x = 1:10, y = "hello")

This creates a new object of class myclass with values for x and y slots.

In summary, objects and classes are an essential part of R programming language. Understanding R's built-in classes and how to define custom classes is important for developing efficient and maintainable code in R.