Explicit Coercion in R Programming
Coercing of an object from one type of class to another is known as explicit coercion. It is achieved through some functions which are similar to the base functions. But they differ from base functions as they are not generic and hence do not call S3 class methods for conversion.
Difference between conversion, coercion and cast:
Normally, whatever is converted implicitly is referred to as coercion and if converted explicitly then it is known as casting. Conversion signifies both types- coercion and casting.
Explicit coercion to character
There are two functions to do so as.character() and as.string().
If v is a vector which is needed to be converted into character then it can be converted as:
- as.character(v, encoding = NULL)
- as.string(v, encoding = NULL)
Here encoding parameter informs R compiler about encoding of the vector and helps internally in managing character and string vectors.
Python3
# Creating a list x< - c( 0 , 1 , 0 , 3 ) # Converting it to character type as.character(x) |
Output:
[1] "0" "1" "0" "3"
Explicit coercion to numeric and logical
They all are as * functions with only one parameter, that is, a vector which is to be converted.
.Difference-table { border-collapse: collapse; width: 100%; } .Difference-table td { text-color: black !important; border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .Difference-table th { border: 1px solid #5fb962; padding: 8px; } .Difference-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .Difference-table tr:nth-child(odd) { background-color: #ffffff; }Â
Function | Description |
---|---|
as.logical |
Converts the value to logical type.
|
as.integer | Converts the object to integer type |
as.double | Converts the object to double precision type |
as.complex | Converts the object to complex type |
as.list | It accepts only dictionary type or vector as input arguments in the parameter |
Python3
# Creating a list x< - c( 0 , 1 , 0 , 3 ) # Checking its class class (x) # Converting it to integer type as.numeric(x) # Converting it to double type as.double(x) # Converting it to logical type as.logical(x) # Converting it to a list as. list (x) # Converting it to complex numbers as. complex (x) |
Output:
[1] "numeric" [1] 0 1 0 3 [1] 0 1 0 3 [1] FALSE TRUE FALSE TRUE [[1]] [1] 0 [[2]] [1] 1 [[3]] [1] 0 [[4]] [1] 3 [1] 0+0i 1+0i 0+0i 3+0i
Producing NAs
NAs are produced during explicit coercion if R is not able to decide the way to coerce some object.
Python3
# Creating a list x< - c("q", "w", "c") as.numeric(x) as.logical(x) |
Output:
[1] NA NA NA Warning message: NAs introduced by coercion [1] NA NA NA
Please Login to comment...