Explicit Coercion in R Programming

Explicit Coercion and Their Types

Explicit coercion refers to the process of converting an object from one type of class to another using specific functions. These functions are similar to base functions but differ in that they are not generic and do not call S3 class methods for conversion.

Difference Between Conversion, Coercion, and Casting
  • Coercion: Refers to implicit conversion of data types.
  • Casting: Refers to explicit conversion of data types.
  • Conversion: A general term that encompasses both coercion and casting.
Explicit Coercion to Character

To explicitly convert an object to a character type, two functions can be used: as.character() and as.string(). The encoding parameter informs the R compiler about the encoding of the vector and assists in managing character and string vectors.

Example:

# Creating a vector
v <- c(10, 20, 30, 40)

# Converting to character type
as.character(v)

Output:

[1] "10" "20" "30" "40"
Explicit Coercion to Numeric and Logical

Explicit coercion to numeric, logical, or other data types is done using as.* functions, where the * represents the target data type. These functions take a vector as their parameter.

Function Descriptions

FunctionDescription
as.logicalConverts values to logical type.0 is converted to FALSE.Non-zero values are 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.listAccepts a vector or dictionary as input.

Example:

# Creating a vector
x <- c(0, 1, 2, 3)

# Checking the class of the vector
class(x)

# Converting to integer type
as.integer(x)

# Converting to double type
as.double(x)

# Converting to logical type
as.logical(x)

# Converting to a list
eas.list(x)

# Converting to complex type
as.complex(x)

Output:

[1] "numeric"
[1] 0 1 2 3
[1] 0 1 2 3
[1] FALSE  TRUE  TRUE  TRUE
[[1]]
[1] 0

[[2]]
[1] 1

[[3]]
[1] 2

[[4]]
[1] 3

[1] 0+0i 1+0i 2+0i 3+0i
Handling NAs During Coercion

If R cannot determine how to coerce an object, it will produce NA values and issue a warning.

Example:

# Creating a vector with non-numeric values
x <- c("apple", "banana", "cherry")

# Attempting to convert to numeric
as.numeric(x)

# Attempting to convert to logical
as.logical(x)

Output:

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *