Sequence Class

I can create a sequence of numbers in one of three ways:

> 1:4 [1] 1 2 3 4 > seq(1,4) [1] 1 2 3 4 > c(1,2,3,4) [1] 1 2 3 4 

But why does c() return another class?

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

EDIT: Added seq() to the discussion.

+7
r
source share
1 answer

The Value section in help(":") tells you what the colon operator returns. It says:

... will be of type integer if from is an integer, and the result is represented in an R-integer type.

So, if from can be represented as an integer, the whole vector will be forcibly bound to an integer

 > class(1.0:3.1) [1] "integer" > 1.0:3.1 [1] 1 2 3 

Usually in R, 1 is numeric . If you want integer , you need to add L

 > class(1) [1] "numeric" > class(1L) [1] "integer" 

In addition, c will force all arguments to a common type, which is the return type "(from ?c ). Which type, which is", is determined from the highest type of components in the hierarchy NULL <raw <logical <integer <double <complex < character <list <expression.

So, if any argument c more general than integer , the whole vector will be forced into a more general class.

 > class(c(1L, 2L, 3L, 4L)) [1] "integer" > class(c(1L, 2, 3L, 4L)) # 2 is numeric, so the whole vector is coerced to numeric [1] "numeric" > class(c(1L, 2, "3L", 4L)) # "3L" is character, so the whole vector is coerced to character [1] "character" 

Re: case seq ,

seq(1, 4) is identical to 1:4 as indicated in ?seq

seq (from, to) "generates a sequence from, from +/- 1, ..., to (identical from: to)"

+13
source share

All Articles