1

I am setting up a vector data, and want to extract a part of it.

I tried two methods, as shown below. I thought these should have the same output, but results are different. Why?

data1<- c( 1, 2, 3, 4, 5 )

data1[ length( data1 ) - 2 : length( data1 ) ]    
# ; [1] 3 2 1

data1[ 3 : 5 ]    
# ; 3 4 5
M--
  • 25,431
  • 8
  • 61
  • 93
Ala
  • 25
  • 2
  • 1
    unrelated to the question of why these are different, in case you didn't know, there's also `tail(data1, 3)` for this kind of subset (some number of elements at the end) – IceCreamToucan Oct 01 '19 at 22:34

1 Answers1

1

Because of operator precedence (check ?Syntax - unary -, + is above sequence operator :), wrap it with () to evaluate as a block

data1[(length(data1)-2):length(data1)]
#[1] 3 4 5

length( data1 ) - 2 : length( data1 )
#[1] 3 2 1 0

(length( data1 ) - 2) : length( data1 )
#[1] 3 4 5
akrun
  • 874,273
  • 37
  • 540
  • 662