I was working my way through a primer on R programming and noticed a slight anomaly :
x <- c(2,1,1,5)
produces a vector of type num
y <- c(1:5)
produces a vector of type int
z <- c(1.5,2.3)
produces a vector of type num
Why does this happen ? What is the fundamental data type in R
: is it int
or is it num
? What happens if one of the elements in the vector is a float
, does the type of the vector become float
or is it something else ? What happens when all the elements in the vector are float
- why is it still num
in that case ?
Basically,numeric class can contain both integers and floating numbers but integer class can contain only integers.
numeric is a general test to check whether a vector is numeric or not. It will return TRUE only if the object passed to it is a vector and consists of only numeric data. Whereas, is. vector tests whether the object is a vector or not.
double is the name of the type. numeric is the name of the mode and also of the implicit class. As an S4 formal class, use "numeric" . The potential confusion is that R has used mode "numeric" to mean 'double or integer', which conflicts with the S4 usage.
There are two distinct issue at play:
In c(2, 1, 1, 5)
you are explicitly creating numeric
types. For integer
, you would have to use c(2L, 1L, 1L, 5L)
as only the suffix L
ensures creation of an integer
type (or casting via as.integer()
etc). But read on ...
In c(1:5)
a historical override for the :
comes into play. Because the usage almost always involves integer sequences, this is what you get: integers.
Both forms are documented, so it is not an anomaly as your question title implies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With