Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading