Hasnain
Hasnain

Reputation: 679

What is the difference between objects and variables?

I want to know the difference between Variables and Objects in R. Is 'a'in the code provided an object or variable ? Where this a is going to be save, in heap or stack ?

a <- 1

Upvotes: 3

Views: 3762

Answers (2)

Abdul Rafay Jungsher
Abdul Rafay Jungsher

Reputation: 516

We can do object oriented programming in R. In fact, everything in R is an object.

An object is a data structure having some attributes and methods which act on its attributes.

Class is a blueprint for the object. We can think of class like a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house.

House is the object. As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

While most programming languages have a single class system, R has three class systems. Namely, S3, S4 and more recently Reference class systems.

They have their own features and peculiarities and choosing one over the other is a matter of preference. Below, we give a brief introduction to them.

S3 class is somewhat primitive in nature. It lacks a formal definition and object of this class can be created simply by adding a class attribute to it.

create a list with required components

s <- list(name = "Rafay", age = 21, GPA = 3.72)

name the class appropriately

class(s) <- "student"

S4 class are an improvement over the S3 class. They have a formally defined structure which helps in making object of the same class look more or less similar.

< setClass("student", slots=list(name="character", age="numeric", GPA="numeric"))

Now if you're from a c#, c background you must think that When in c# int a =2 #it is called variable Student std1=new Student() ;# it is called object But as mentioned above everything in R is called object.

Upvotes: 1

nicola
nicola

Reputation: 24520

There is no difference, from a data type perspective, between 1 and c(1,2,3). Everything in R is an object. For instance:

a <- 1
b <- c(1,2,3)
typeof(a)==typeof(b)
#[1] TRUE
class(a)==class(b)
#[1] TRUE

R is a high level language and you don't have visibility on where and when R actually allocates memory.

Upvotes: 5

Related Questions