Reputation: 238
I was trying to create a sequence of odd values using the :
operator (like in Octave), when I ran into a weird behavior.
I tried the same operation with different values.
> 1:2:10
[1] 1 2 3 4 5 6 7 8 9 10
Warning message:
In 1:2:10 : numerical expression has 2 elements: only the first used
> 1:0.2:10
[1] 1 2 3 4 5 6 7 8 9 10
> 1:0.5:10
[1] 1 2 3 4 5 6 7 8 9 10
> 1:0.9:10
[1] 1 2 3 4 5 6 7 8 9 10
> 1:1.9:10
[1] 1 2 3 4 5 6 7 8 9 10
> 1:2.9:10
[1] 1 2 3 4 5 6 7 8 9 10
Warning message:
In 1:2.9:10 : numerical expression has 2 elements: only the first used
> 1:3.9:10
[1] 1 2 3 4 5 6 7 8 9 10
Warning message:
In 1:3.9:10 : numerical expression has 3 elements: only the first used
I don't understand the difference. I would like to know why sometimes I get a warning and other times not and the difference in warning messages. I know I have to use seq
to get the odd values I wanted, but this inconsistent behavior puzzles me.
Upvotes: 2
Views: 54
Reputation: 26363
When you do
1:1.9
the result is
# 1
and so 1:1.9:10
is the same as 1:10
.
But when you call
1:2
you get
# 1 2
Hence 1:2:10
is the same as calling
c(1, 2):10 # which gives 1:10 see warning
# [1] 1 2 3 4 5 6 7 8 9 10
#Warning message:
#In c(1, 2):10 : numerical expression has 2 elements: only the first used
From the help page:
Arguments
from : starting value of sequence.
to : (maximal) end value of the sequence.
...
Value to will be included if it differs from from by an integer up to a numeric fuzz of about 1e-7.
Upvotes: 6