0

In R, when I add 0 (or a variable that has a value of 0) to each index of a slice, I end up with a result that is one element longer than I expect.
Why is this, and how can I achieve the 1 2 3 4 5 result I expect?

my_vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

my_vec[1 : 5] 
my_vec[1 + 0 : 5 + 0]

returns

1 2 3 4 5     # my_vec[1 : 5]
1 2 3 4 5 6   # my_vec[1+0 : 5+0]
  • 1
    this is a order of operations issue. try `my_vec[(1+0):(5+0)]` – langtang Jun 30 '22 at 18:34
  • I'd just add that `:` should not be considered as slice, it's a sequence operator. Might not sound like it matters, but it returns a vector, so `1 + 0 : 5 + 0` evaluates pretty much the same as `1 + seq(0,5)` . And when coming from Python, this can bite quite hard .. – margusl Jun 30 '22 at 19:01

1 Answers1

1

Try using parentheses so that the addition operation is executed first:

my_vec[(1+0):(5+0)]

Output:

[1] 1 2 3 4 5
langtang
  • 22,248
  • 1
  • 12
  • 27