R Language: Explicit Coercion

0
Explicit coercion is the process of converting an object from one class to another using the `as.<class>` functions. The `as.<class>` functions are available for all of the basic classes in R.

For example, the following code explicitly coerces an integer object to a character object:

x <- 0:6
class(x)
[1] "integer"
as.character(x)
[1] "0" "1" "2" "3" "4" "5" "6"

As you can see, the `as.character()` function successfully coerced the integer object to a character object.

Sometimes, R cannot figure out how to coerce an object and this can result in NAs being produced. For example, the following code tries to coerce a character object to a numeric object:

x <- c("a", "b", "c")
as.numeric(x)
Warning: NAs introduced by coercion
[1] NA NA NA

As you can see, the `as.numeric()` function was not able to coerce the character object to a numeric object. Instead, it produced NAs.

When nonsensical coercion takes place, you will usually get a warning from R. This is a good way to check if your coercion is working as expected.

Post a Comment

0Comments
Post a Comment (0)