huoenter
huoenter

Reputation: 522

R: slicing vectors by variable indices

I wonder why R acts weird when slicing a vector using variable indices. (I am trying to write a simple function to get moving averages.) e.g.:

v <- c(1,2,3,4)
v[2:3] # works: [1] 2 3
i <-2
v[i:i+1] # gives "3" only

(I found the filter() solution.) I wonder if it is not allowed or there's something wrong how I used it. (RStudio 1.0.153, R 3.4.0)

Upvotes: 0

Views: 55

Answers (1)

Wietze314
Wietze314

Reputation: 6020

Use parenthesis:

> v <- c(1,2,3,4)
> v[2:3] 
[1] 2 3
> i <-2
> v[i:(i+1)] 
[1] 2 3
> v[2:3] 
[1] 2 3
> i <-2
> v[i:(i+1)]
[1] 2 3

Upvotes: 2

Related Questions