I want to calculate the moving sum with varying window sizes of 1:15.
a <- matrix(0,257,15)
b <- c(1:257)
for(j in 1:15) {
for(i in j:257) {
a[i,j] <- sum(b[i-j+1:i])
}
}
However, the above code gives cases me confusion, as it yields NA
after the 129th row in every column. What could be reason for such behaviour?
Add parentheses (...):i
into indexing of b[(i-j+1):i]
in order to properly have a range between i-j+1
and i
. The full code then reads as
a <- matrix(0,257,15)
b <- c(1:257)
for (j in 1:15) {
for (i in j:257) {
a[i,j] <- sum(b[(i-j+1):i])
}
}
As an example on the importance of the parentheses, you may compare the calculating order of the following three cases:
> (1+1):2
[1] 2
> 1+1:2
[1] 2 3
> 1+(1:2)
[1] 2 3
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments