seq(1, 10) or seq(1:10)

Hello,
I would like to ask question about the difference between using seq(1, 10) and seq(1:10) in R code.
Is there any mistake to use seq(1:10) when we like to generate the vector 1 2 3 4 5 6 7 8 9 10
Thank you in advance.
Redha

is fine, as is

seq(1,10)

The function also takes arguments for various options. See help(seq)

seq(0, 1, length.out = 11)
#>  [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
seq(stats::rnorm(20)) # effectively 'along'
#>  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
seq(1, 9, by = 2)     # matches 'end'
#> [1] 1 3 5 7 9
seq(1, 9, by = pi)    # stays below 'end'
#> [1] 1.000000 4.141593 7.283185
seq(1, 6, by = 3)
#> [1] 1 4
seq(1.575, 5.125, by = 0.05)
#>  [1] 1.575 1.625 1.675 1.725 1.775 1.825 1.875 1.925 1.975 2.025 2.075 2.125
#> [13] 2.175 2.225 2.275 2.325 2.375 2.425 2.475 2.525 2.575 2.625 2.675 2.725
#> [25] 2.775 2.825 2.875 2.925 2.975 3.025 3.075 3.125 3.175 3.225 3.275 3.325
#> [37] 3.375 3.425 3.475 3.525 3.575 3.625 3.675 3.725 3.775 3.825 3.875 3.925
#> [49] 3.975 4.025 4.075 4.125 4.175 4.225 4.275 4.325 4.375 4.425 4.475 4.525
#> [61] 4.575 4.625 4.675 4.725 4.775 4.825 4.875 4.925 4.975 5.025 5.075 5.125
seq(17) # same as 1:17, or even better seq_len(17)
#>  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17

Thank you a lot for your answer.
Best regards,
Redha

Just to build a bit on the previous answer: while it is correct that seq(1, 10) and seq(1:10) are equivalent in result I don't think that combining colon operator and seq() function is the best of practices.

The reason is that in the seq(1:10) the sequence is generated in the 1:10 call, and the seq around it just wraps itin another sequence of length one.

To illustrate the point consider this seq(1:10, by = 2) which clearly is not equivalent to seq(1, 10, by = 2).

While it is to a certain extent a matter of style & taste I suggest sticking to the colon operator when an integer sequence of step one is desired.

2 Likes

I agree that 1:10 should be limited to that case.

Thank you for your answer.
Best regards,
Redha

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.