R index variable in vector does not work as excected

I want to make sort of sliding window, putting a variable of start and end position on each iteration.
But I’ve noticed calculation inside of square brackets does not work.

t <- c(1, 2, 3, 4, 5)
i <- 1
t[i:i + 3]

this gives "4".
Seems like index is calculated but start value of 1 is ignored.

If I introduce j variable, then it works as expected

t <- c(1, 2, 3, 4, 5)
i <- 1
j <- i + 3
t[i: j]

So the question is what’s going on in first piece of code?

>Solution :

In your code the addition is done before indexing:

Try this:

t <- c(1, 2, 3, 4, 5)
i <- 1
t[(i):(i + 3)]
[1] 1 2 3 4

Leave a Reply