Skip to content
Related Articles

Related Articles

Explicit Coercion in R Programming
  • Last Updated : 01 Jun, 2020

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 list
x<-c(0, 1, 0, 3)
  
# Converting it to charcter 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.

FunctionDescription

as.logical

Converts the value to logical type.

  • If 0 is present then it is converted to FALSE
  • Any other value is converted to TRUE
as.integerConverts the object to integer type
as.doubleConverts the object to double precision type
as.complexConverts the object to complex type
as.listIt accepts only dictionary type or vector as input arguments in the parameter




# 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.




# 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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :