R Language: Mixing Objects

0

Mixing objects in R happens when you try to combine objects of different classes in a vector. For example, the following code tries to combine a numeric object (1.7) with a character object ("a"):

y <- c(1.7, "a")

R will automatically coerce the numeric object to a character object, so that the vector will contain all character objects. This is because R tries to find a way to represent all of the objects in the vector in a reasonable fashion. In this case, it is reasonable to represent the numeric object as a string, because numbers can usually be easily represented as strings.

The following table shows the rules for implicit coercion in R:

As you can see, the rules for implicit coercion are not always intuitive. For example, logical objects are coerced to character objects, even though they could be coerced to numeric objects. This is because R tries to be as conservative as possible when coercing objects.

It is important to be aware of implicit coercion when you are working with vectors in R. If you do not want objects to be coerced, you can use the `as.<class>` function to explicitly coerce the objects to the desired class. For example, the following code explicitly coerces the numeric object to a character object:

y <- as.character(1.7)

This will prevent R from coercing the numeric object to a character object implicitly.

Post a Comment

0Comments
Post a Comment (0)