Coercion in R
Share
Coercion :
Coercion includes type conversion . Type conversion means change of one type of data into another type of data. We have to type of coercion occurs :
1. Implicit Coercion
2. Explicit Coercion
Explicit Coercion :
In explicit coercion , we can change one data type to another data type by applying function.
We create an object “x” which stores integer values from 1 to 6.
x<-0:6
We can check data type of “x” object.
class(x)
We used as.numeric() to change integer data type to numeric data type.
z<-as.numeric(x)
We check data type of z. It shows “numeric” data type.
class(z)
We can also change character data to numeric data as:
We also changed logical data to character data.
We also changed integer data to Logical data as:
When we changed numeric or integer to logical data , it will store 0 as FALSE and other values as TRUE. You can see here also .
Some exceptions of explicit coercion :-
We are converting character data type to numeric data type. It will show NA . It will show missing in out object. It will not change character data to numeric because it includes values “a” which cannot be changed to numeric data.
Implicit Coercion :
When type conversion occurs by itself in R.
We input numeric and character data in an object . R converts numeric data to character data by itself.
We input logical and numeric data in an object . Logical data convert to numeric data implicitly.
There are many types of objects to store R-object . The frequently used objects are –
- Vectors
- Matrices
- Arrays
- Factors
- Data Frames
- Lists
- Table