0
(1:10)[2:5]
# [1] 2 3 4 5
(1:10)[2 + 1:5 + 1]
# [1] 4 5 6 7 8
(1:10)[(2 + 1):(5 + 1)]
# [1] 3 4 5 6
(1:10)[10 + 1:5 + 1]
# [1] NA NA NA NA NA

I am learning how list access works in R. The second case from the above looks weird. Can someone explain how that pattern is working ?

(1:10)[2 + 1:5 + 1]

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Ninja420
  • 3,542
  • 3
  • 22
  • 34
  • 1
    1+3 = 4, 2+3 = 5. You are adding three to every value in 1:5 then indexing – Dodge Apr 28 '18 at 00:39
  • @W.Dodge Why does `(1:10)[10 + 1:5 + 1]` give `NA NA NA NA NA` then ? It should ideally be indexing `1:5` and adding `11` ? – Ninja420 Apr 28 '18 at 00:52
  • Because you have added 11 to 1:5 which generates 12,13,14,15,16. You then index 1:10 by those five values which are out of range and get five NAs. – Dodge Apr 28 '18 at 00:55

1 Answers1

2

Vector Math

R allows for vectors to be treated like individual numbers. Here is a link to nice tutorial on vector math. I bet you already knew this but the configuration was just a little unusual in this case. Your test case basically adds three (1+2) to the vector 1:5 then indexes.

Test:

> (1:10)[1+1:5+2] == (1:10)[1:5+3] [1] TRUE TRUE TRUE TRUE TRUE

Dodge
  • 3,219
  • 3
  • 19
  • 38