向量中的R索引变量未按预期工作。

huangapple go评论67阅读模式
英文:

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 &lt;- c(1, 2, 3, 4, 5)
i &lt;- 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 &lt;- c(1, 2, 3, 4, 5)
i &lt;- 1
j &lt;- i + 3
t[i: j]

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

答案1

得分: 2

在你的代码中,加法是在索引之前完成:

尝试这样做:

t &lt;- c(1, 2, 3, 4, 5)
i &lt;- 1
t[(i):(i + 3)]
[1] 1 2 3 4
英文:

In your code the addition is done before indexing:

Try this:

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

huangapple
  • 本文由 发表于 2023年5月21日 02:20:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定