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.
# Creating a listx<-c(0, 1, 0, 3) # Converting it to charcter typeas.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.
| 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 |
# Creating a listx<-c(0, 1, 0, 3) # Checking its classclass(x) # Converting it to integer typeas.numeric(x) # Converting it to double typeas.double(x) # Converting it to logical typeas.logical(x) # Converting it to a listas.list(x) # Converting it to complex numbersas.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.
# Creating a listx<-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


.png)