Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : Int vs Num Anomaly in Vector

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 ?

like image 488
pranav Avatar asked Apr 26 '15 14:04

pranav


People also ask

What is the difference between NUM and INT in R?

Basically,numeric class can contain both integers and floating numbers but integer class can contain only integers.

What is the difference between is vector () and is numeric () functions in R?

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.

What is the difference between double and numeric in R?

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.


1 Answers

There are two distinct issue at play:

  1. 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 ...

  2. 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.

like image 136
Dirk Eddelbuettel Avatar answered Oct 03 '22 14:10

Dirk Eddelbuettel