英文:
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 the first piece of code?
英文:
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?
答案1
得分: 2
在你的代码中,加法是在索引之前完成:
尝试这样做:
t <- c(1, 2, 3, 4, 5)
i <- 1
t[(i):(i + 3)]
[1] 1 2 3 4
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论