top of page
Writer's pictureEkta Aggarwal

class function in R

In this tutorial we will learn about how to get the 'class' i.e., the datatype of various objects in R.


For this, we will make use of iris dataset, which is inbuilt in R. Let us firstly view the iris dataset using View command.

View(iris)

iris has got information abotu 5 different attribtutes for 150 flowers. Thus, the shape of the dataset is 150 rows and 5 columns.

Let us firstly create a copy of this iris dataset called data. In this tutorial we will use this 'data'

data = iris

Using class function one can get to know the datatype of an object. The various datatypes available are:

  • numeric

  • character

  • factor

  • date

  • matrix

  • dataframe

  • list

For learning in detail about these datatypes you can refer to this tutorial: Types of objects in R


Let us use the class function on our object called 'data'. For this we write our object name inside the parenthesis ( ) of class function.

class(data)

In the output we can see that it is a dataframe.

Output: "data.frame"


Now let us consider a columns names 'Petal.Length' from the 'data'. We know it is a vector. But class function tells the variable type of that vector:


class(data$Petal.Length)

In the output we can see that it is 'numeric' as it is a numeric vector.

Output: "numeric"



Now let us consider a columns names 'Species' from the 'data'.

class(data$Species)

In the output we can see that it is 'factor' as it is 3 different classes: Setosa, Versicolor and Virginica.

Output: "factor"



Let us create another column names 'Species_char' where we are converting the 'Species' column to character using 'as.character' function.

data$Species_char = as.character(data$Species)

Now let us apply class function for our new column 'Species_char'.

class(data$Species_char)

In the output we can see that it is 'character'

Output: "character"

Kommentare


bottom of page