-4

How do I generate a vector with a specified increment step (e.g. 2)? For example, how do I produce the following

1,3,5,7,9,11,13,15,17,19

I want to do it with the function 1:19 with the jump of 2.

I know the seq function, I want to know if there is a way to create the vector in this way 1:19(with jumps of 2) ?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Check `?seq`... – Ronak Shah Mar 22 '21 at 12:29
  • Thanks for the answer, i know the seq function. i want to know if there is a way to create the vector in this way 1:19(with jumps of 2) – Yoav Scheinfeld Mar 22 '21 at 12:30
  • 2*(1:10)-1 or 2*(0:9)+1 – G. Grothendieck Mar 22 '21 at 12:45
  • Welcome to Stack Overflow! Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221) – Sabito stands with Ukraine Mar 22 '21 at 12:50
  • 3
    Since yo know the `seq` function, you should know that it contains a `by` argument, which does exactly what you want. – desertnaut Mar 22 '21 at 12:58
  • Possible duplicate of "extract every nth" https://stackoverflow.com/q/5237557/680068 – zx8754 Mar 22 '21 at 13:04

2 Answers2

3

Use seq (type ?seq into the R console for details):

vec = seq(1, 19, 2)

where from = 1, to = 19, by = 2.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
trevelyan
  • 33
  • 5
3

You can use a logical vector (length 2 but which will be recycled) to subset 1:19:

(1:19)[c(TRUE, FALSE)]
# [1]  1  3  5  7  9 11 13 15 17 19
s_baldur
  • 29,441
  • 4
  • 36
  • 69
Cath
  • 23,906
  • 5
  • 52
  • 86