Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Explicit Coercion in R Programming

  • Difficulty Level : Easy
  • 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


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



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
# Converting it to integer type
# Converting it to double type
# Converting it to logical type
# Converting it to a list
# Converting it to complex numbers


[1] "numeric"
[1] 0 1 0 3
[1] 0 1 0 3
[1] 0

[1] 1

[1] 0

[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")


[1] NA NA NA
Warning message:
NAs introduced by coercion 
[1] NA NA NA

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!