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.
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:
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.
In the output we can see that it is a dataframe.
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:
In the output we can see that it is 'numeric' as it is a numeric vector.
Now let us consider a columns names 'Species' from the 'data'.
In the output we can see that it is 'factor' as it is 3 different classes: Setosa, Versicolor and Virginica.
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'.
In the output we can see that it is 'character'