Colon
Colon Operator
Generate regular sequences.
- Keywords
- manip
Usage
from:to a:b
Arguments
- from
- starting value of sequence.
- to
- (maximal) end value of the sequence.
- a, b
factor
s of the same length.
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"
).For factors, an unordered factor with levels labelled as la:lb
and ordered lexicographically (that is, lb
varies fastest).
References
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
The New S Language.
Wadsworth & Brooks/Cole.
(for numeric arguments: S does not have :
for factors.)
See Also
seq
(a generalization of from:to
).
As an alternative to using :
for factors, interaction
.
For :
used in the formal representation of an interaction, see
formula
.
Examples
library(base)
1:4
pi:6 # real
6:pi # integer
f1 <- gl(2, 3); f1
f2 <- gl(3, 2); f2
f1:f2 # a factor, the "cross" f1 x f2
Community examples
`a:b` is a conveniently easy to type alternative to [`seq.int(a, b)`](https://www.rdocumentation.org/packages/base/topics/seq) ```{r} -3:6 seq.int(-3, 6) ``` You can also have `b` less than `a` ```{r} 6:-3 ``` Sequences don't have to start at a whole number. ```{r} -2.63:6.37 ``` If `b - a` isn't a whole number, then the last fraction is ignored. ```{r} (e_to_the_e <- exp(exp(1))) 0:e_to_the_e ``` If `a` is a whole number, then the result has class `integer` (even if `a` has class `numeric`). ```{r} class(3) class(-3:6) ``` Be careful, `1:n` is tricksy when `n = 0` – this is a common source of bugs. Use [`seq_len()`](https://www.rdocumentation.org/packages/base/topics/seq) instead for this case. ```{r} n <- 3 1:3 n <- 0 1:n seq_len(n) ```