<- c(TRUE, FALSE)
my_logi typeof(x = my_logi)
[1] "logical"
The R programming language is extremely useful for a variety of data science tasks. It–and other object-oriented programming languages–allow storing values in “objects” and then using those objects to re-call and use the values to which they are bound. In order to combine different “types” of values, R has to “coerce” one or both of the values into a shared type (sometimes a.k.a. “class” depending on what you’re working on).
The order of this coercion is logical -> integer -> double -> character
. Logicals are the most specific type of atomic vector and the order proceeds to characters which are the most general type. It might be helpful to consider some examples. Let’s begin by making one object for each atomic type (identified above).
Now that we have those, let’s combine them in sequence so we can see the coercion rules in action!
You may have noticed that the above examples are missing some classes of object with which you may work regularly. These were absent from the above examples because the first component of this tip is restricted only to “type” coercion while you may be thinking of “class” coercion. See below for some examples that may address what felt missing above.
“Numeric” values are technically inclusive of both integers and doubles. The reason to avoid that phrasing earlier was just to be more precise about the coercion rules between integers and doubles.
Factors are a special case of an integer. This does mean that coercing a factor can have surprising results in some cases.
[1] a b c
Levels: a b c
Dates are a special case of a double. They represent the number of days since January 1st, 1970. Like factors, this means that coercion can behave in a way that surprises you.
Date-times are a special case of a double. They represent the number of seconds since January 1st, 1970. Just like dates, this can make coercion surprising here as well.
# Make a datetime
my_datetime <- as.POSIXct("2024-10-13 23:00", tz = "UTC")
# Check the type & class
typeof(x = my_datetime)
[1] "double"
[1] "POSIXct" "POSIXt"
# Coerce it by combining with a character
my_char.datetime <- c(my_char, my_datetime)
my_char.datetime
[1] "a" "b" "c" "1728860400"
[1] "character"