Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class of a sequence of numbers

Tags:

r

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 a different 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.

like image 366
stackoverflowuser2010 Avatar asked Aug 05 '13 00:08

stackoverflowuser2010


People also ask

What is the sequence of class?

Sequences encapsulate user-defined procedures that generate multiple uvm_sequence_item-based transactions. Such sequences can be reused, extended, randomized, and combined sequentially and hierarchically in interesting ways to produce realistic stimulus to your DUT.

What are the 4 types of sequences?

There are four main types of different sequences you need to know, they are arithmetic sequences, geometric sequences, quadratic sequences and special sequences.

What are the 3 types of sequences?

There are mainly three types of sequences: Arithmetic Sequences. Geometric Sequence. Fibonacci Sequence.

What is the sequence of numbers?

Number sequence is a progression or an ordered list of numbers governed by a pattern or rule. Numbers in a sequence are called terms. A sequence that continues indefinitely without terminating is an infinite sequence, whereas a sequence with an end is known as a finite sequence.


1 Answers

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

... will be of type integer if from is integer-valued and the result is representable in the R integer type.

So, if from can be represented as an integer, the whole vector is coerced to integer

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

Generally in R, 1 is numeric. If you want an integer, you have to append an L

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

Furthermore, c will coerce all arguments "to a common type which is the type of the returned value" (from ?c). What type that is "is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression."

So, if any argument to c is more general than integer, the whole vector will be coerced to the 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: the seq case,

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

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

like image 167
GSee Avatar answered Nov 07 '22 01:11

GSee