Reputation: 522
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
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