The Class of an Object In R Language

Introduction to Class of an Object in R

In R language, all objects have a class, which can be reported using the class() function. For simple vectors, this is just the mode, such as numeric, character, list, or logical. The other possible modes are array, matrix, factor, and data frame.

A special attribute known as the class of the object is used to allow for an object-oriented style of programming in R language. For example, an object having class as “data.frame” will be printed in a certain way, the plot() function will display it graphically in a certain way, and other generic functions such as summary() will react to it as an argument in a way sensitive to its class.

How to Determine the Class of an Object in R

The class() function is used to determine the class of an object. For example,

class(mtcars)
x <- c(1, 2, 3)
class(x)

y <- c("a", "b", "c")
class(y)

z <- c(TRUE, FALSE)
class(z)
Class of an Object in R Language

Common Object Classes in R

Here are some of the most common object classes in R:

  1. Integer: Represents integer values.
  2. Numeric: Represents numerical data.
  3. Character: Represents text strings.
  4. Factor: Represents categorical data.
  5. Logical: Represents logical values (TRUE or FALSE).
  6. Date: Represents dates.
  7. List: Represents a collection of objects of different types.
  8. Matrix: Represents a two-dimensional array of numbers.
  9. Data Frame: Represents a tabular data structure with rows and columns.
  10. POSIXct: Represents date and time.

It is important to note that one can define one’s classes using S3 or S4 object-oriented systems. This allows the user to define specific methods and behavior for different objects.

Why Classes Matter in R Language

The class of an object determines how R behaves when a user applies functions to it. In simple words, a class defines the object’s type and determines the operations that can be performed on it. For instance:

  • Arithmetic operations: These are typically performed on numeric objects.
  • String manipulation: These are performed on character objects.
  • Statistical analysis: These are often performed on numeric or factor objects.

The importance of classes can be described as:

  • Method Dispatch: The class of an object in R language determines which function to call when you apply a generic function to it. For example, the summary() function behaves differently for numeric vectors, data frames, and linear models.
  • Object-Oriented Programming: R supports object-oriented programming, and classes are fundamental to this paradigm. One can create custom classes to represent complex data structures and define methods to operate on these objects.
  • Data Manipulation: Understanding the class of an object helps one to choose the appropriate functions for data manipulation. For instance, one might use different functions for subsetting, sorting, and summarizing numeric vectors, character vectors, and data frames.

Remove the Class of an Object in R

To remove temporarily the effect of a class from an object, one can use the unclass() function. For example, if mtcars has the class “data.frame” then typing the just mtcars on the command prompt will print it in data frame form, which is rather like a matrix.

mtcars

Whereas, typing unclass(mtcars) will print/display it as an ordinary list.

unclass(mtcars)

## Output
$mpg
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4

$cyl
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

$disp
 [1] 160.0 160.0 108.0 258.0 360.0 225.0 360.0 146.7 140.8 167.6 167.6 275.8 275.8 275.8 472.0 460.0 440.0  78.7  75.7  71.1 120.1 318.0 304.0 350.0 400.0  79.0 120.3  95.1 351.0 145.0 301.0 121.0

$hp
 [1] 110 110  93 110 175 105 245  62  95 123 123 180 180 180 205 215 230  66  52  65  97 150 150 245 175  66  91 113 264 175 335 109

$drat
 [1] 3.90 3.90 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 3.92 3.07 3.07 3.07 2.93 3.00 3.23 4.08 4.93 4.22 3.70 2.76 3.15 3.73 3.08 4.08 4.43 3.77 4.22 3.62 3.54 4.11

$wt
 [1] 2.620 2.875 2.320 3.215 3.440 3.460 3.570 3.190 3.150 3.440 3.440 4.070 3.730 3.780 5.250 5.424 5.345 2.200 1.615 1.835 2.465 3.520 3.435 3.840 3.845 1.935 2.140 1.513 3.170 2.770 3.570 2.780

$qsec
 [1] 16.46 17.02 18.61 19.44 17.02 20.22 15.84 20.00 22.90 18.30 18.90 17.40 17.60 18.00 17.98 17.82 17.42 19.47 18.52 19.90 20.01 16.87 17.30 15.41 17.05 18.90 16.70 16.90 14.50 15.50 14.60 18.60

$vs
 [1] 0 0 1 1 0 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 0 0 1

$am
 [1] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1

$gear
 [1] 4 4 4 3 3 3 3 4 4 4 4 3 3 3 3 3 3 4 4 4 3 3 3 3 3 4 5 5 5 5 5 4

$carb
 [1] 4 4 1 1 2 1 4 2 2 4 4 3 3 3 4 4 4 1 2 1 1 2 2 4 2 1 2 2 4 6 8 2

attr(,"row.names")
 [1] "Mazda RX4"       "Mazda RX4 Wag"    "Datsun 710"       "Hornet 4 Drive"   "Hornet Sportabout"
 [6] "Valiant"         "Duster 360"       "Merc 240D"        "Merc 230"         "Merc 280"
[11] "Merc 280C"       "Merc 450SE"       "Merc 450SL"       "Merc 450SLC"      "Cadillac Fleetwood" 
[16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"      "Honda Civic"     "Toyota Corolla" 
[21] "Toyota Corona"    "Dodge Challenger"  "AMC Javelin"     "Camaro Z28"      "Pontiac Firebird"   
[26] "Fiat X1-9"       "Porsche 914-2"     "Lotus Europa"     "Ford Pantera L"  "Ferrari Dino"       
[31] "Maserati Bora"   "Volvo 142E"

Changing the Class of an Object in R

While it’s generally not recommended to manually change an object’s class, there are functions like as.numeric(), as.character(), as.factor(), etc., that can coerce objects into different classes. However, be cautious, as inappropriate coercion can lead to unexpected results.

Understanding object classes is fundamental to effective R programming. By recognizing the class of an object, you can choose the appropriate functions and operations to work with it. By understanding the class of an object, you can effectively work with R’s diverse data structures and leverage its powerful data analysis capabilities.

FAQs about Class of an Object

  1. What is the concept of class in R language?
  2. How can one check the class of an object?
  3. For different data types (modes) what are the common classes used in R?
  4. How can one change the class of an object?
  5. Give examples to determine the class of different objects.

https://itfeature.com, https://gmstat.com

Generic Functions in R

The generic functions in R Language are objects that determine how the function will treat it. A generic function performs an action (or task) on its arguments specific to the class of the argument itself. A default action will be performed if an argument lacks any class attribute that is if an argument of the function has a class not catered for specifically by the generic function, a default action will be provided.

The class mechanism in R provides the facility of designing and writing generic functions in R for special purposes. For example, the generic functions in R such as

  • the plot() is used for displaying objects graphically,
  • the summary() is used for summarizing analyses of various types of objects
  • the anova() is used for comparing different statistical models
  • the print() is used to display the results of various types of objects

The Generic Functions in R can handle a large number of classes. For example, the function plot() has a default method and variants for different types of objects such as data.frame, density, factor, and many more. A complete list of Generic Functions in R can be obtained by using

methods(plot)
methods(summary)
Generic Functions in R language

The body of a Generic function in R is concise and short. For example,

print

## Output
function (x, ...) 
UseMethod("print")
<bytecode: 0x0000029448a0aa40>
<environment: namespace:base>

From the above code, the body of the Generic Function, UseMethod indicates that this is a generic function.

Key Concepts and Characteristics

The following are key concepts and characteristics of generic functions in R.

  • Dispatch: When an object is passed to a generic function, R determines the appropriate method to execute based on the class of the object provided. This process is known as dispatch.
  • Methods: A method is a specific implementation of a generic function for a particular class of the object. It provides instructions on how the function should behave when applied to certain objects of that class.
  • Class Inheritance: R supports class inheritance, allowing methods defined for a parent class to be inherited by its child classes. This enables generic functions to work seamlessly with objects from different classes within a hierarchy.
  • Default Methods: If no method is defined for a specific class, R will look for a default method. The default method is typically defined for the generic function’s base class or a more generic class.

Benefits of Generic Functions in R

The following are some benefits of using and creating generic functions in R

  • Code Reusability: Generic functions can be used with different types of objects, reducing the need for redundant code.
  • Readability: Generic functions can improve code readability by separating the generic interface from the specific implementations.
  • Polymorphism: Generic functions allow the user to write code that can work with objects of different classes, promoting flexibility and adaptability.
  • Extensibility: New methods can be added for custom classes, making it easy to extend the functionality of generic functions.

Best Practices for Creating Generic Functions in R Language

For creating or writing generic functions, the following are the best practices to follow:

  • Give clear and descriptive names to generic functions and their methods.
  • Define methods for commonly used classes to ensure compatibility.
  • Consider using inheritance to avoid redundant code in methods for related classes.
  • Test the generic functions thoroughly to ensure they work as expected with different types of objects.

Example of Creating Generic Functions

To create/write generic functions in R, define a function with the desired name and arguments. One can then define methods for different classes using the UseMethod function within the body of a generic function. Consider the following example

gf <- function(x) {
  UseMethod("gf")
}

gf.numeric <- function(x) {
  # Method for numeric objects
  mean(x)
}

gf.character <- function(x) {
  # Method for character objects
  nchar(x)
}

In the above exemplary code, gf() is defined as a generic function. The UseMethod() function tells R to dispatch the call to the appropriate method based on the class of the argument x. The gf.numeric and gf.character methods provide specific implementations for numeric and character objects, respectively. Let us check the behaviour of the fg() function created as a generic function

x <- 1:5  # Numeric Vector

gf(x)

## Output
[1] 3

gf("statistics")

## Output
[1] 10

Learn about how to get or view the source code of a function or method.

Frequently Asked Questions About R, Generic Functions in R

https://itfeature.com, https://gmstat.com

Learn How to Create User Defined Functions in R

Introduction to User Defined Functions in R

One can create user defined functions in R Language easily. User-defined functions allow to write/create custom blocks of code to be reused throughout the analysis. The article presents some useful examples of how to write user defined functions in R Language. R language helps to create much more efficient and possibly elegant coding.

Assigning Function to a Variable

Example 1: Create a simple function and assign the function to a variable name as we do with any other objects.

f <- function(x, y = 0){
		z <- x + y
		z
}

x = rnorm(10)
f(x + y)

Regression Coefficients

Example 2: Given $n\times 1$ vector of $y$ and matrix of $X$ the $\hat{\beta}=E[X|y] = (X’X)^{-1}X’y$, where $(X’X)^{-1}$ is generalized invers of $X’X$.

Beta <- function(x, y){
		X <- qr(x)
		qr.coef(X, y)
	}

attach(mtcars)
xmat = cbind(1, hp, wt)
yvar = mpg
regcoef <- Beta(xmat, yvar)

The qr() function computes the QR decomposition of a matrix. The QR decomposition if used to solve the equation $Ax=b$ for a given matrix $A$, and vector $b$. It is very useful in computing regression coefficients and in applying Newton Raphson’s algorithm.

User Defined Functions in R

Removing all Objects from globalenv

Example 3: Create a function capable of removing all objects from the globalenv.

clear <- function(env = globalenv() ){
		obj = ls(envir = env)
		rm(list = obj, envir = env)
}

The clear() function removes all objects from a specified environment and seems to work correctly. However, the clear() function detects also itself and as a result, it cannot be reused without redefining the function again.

The clear() function can be improved to keep the function clear() when all other objects are deleted.

clear <- function(env = globalenv()){
		objects <- objects(env)
		objects <- objects[objects != "clear"]
		rm(list = objects, envir = env)
		invisible(NULL)
	}

Computing Measure of Central Tendency

Example 4: Create a function that can compute some basic Measure of Central Tendency.

center = function(x, type){
	switch(type, 
		mean = mean(x),
		median = median(x),
		trimmed = mean(x, trim = 0.1))
}

attach(airquality)
center(Temp, "mean")     # for calcualtion of mean
center(Temp, "median")   # for calculation of median
center(Temp, "trimmed")  # for calculation of trimmed mean
User defined functions in R: Measure of Central Tendency

Note that the user-defined functions in R can incorporate conditional statements, loops, and other functionalities to perform more advanced tasks. They can also have default parameter values for added flexibility.

https://itfeature.com

https://gmstat.com