Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: why is "identical(c(1:3), c(1, 2, 3))" false?

Tags:

integer

r

double

Why is identical(c(1:3), c(1, 2, 3)) false? In other words, why is the former an integer while the latter is a double?

like image 277
Joe Avatar asked Mar 21 '17 18:03

Joe


2 Answers

R> class(1:3)
[1] "integer"
R> class(c(1,2,3))
[1] "numeric"
R> 

In a nutshell, : as the sequence operator returns integer "because that is what folks really want".

Hence:

R> identical(1:3, c(1L,2L,3L))
[1] TRUE
R> identical(1*(1:3), c(1,2,3))
[1] TRUE
R> 
like image 168
Dirk Eddelbuettel Avatar answered Sep 30 '22 00:09

Dirk Eddelbuettel


It has to do with the colon operator. From ?':' or help(':'):

Details

The binary operator : has two meanings: for factors a:b is equivalent to interaction(a, b) (but the levels are ordered and labelled differently).

For other arguments from:to is equivalent to seq(from, to), and generates a sequence from from to to in steps of 1 or -1. Value to will be included if it differs from from by an integer up to a numeric fuzz of about 1e-7. Non-numeric arguments are coerced internally (hence without dispatching methods) to numeric—complex values will have their imaginary parts discarded with a warning.

Value

For numeric arguments, a numeric vector. This will be of type integer if from is integer-valued and the result is representable in the R integer type, otherwise of type "double" (aka mode "numeric").

like image 23
Fernando Avatar answered Sep 30 '22 00:09

Fernando