The error is due to the well-known R gotcha that the :
(seq
operator) takes lower precedence than arithmetic.
So a[i-3:i]
doesn't do what you want it to do a[(i-3):i]
, it does a[i - (3:i)])
. So the medians you are printing are of:
4-3:1 # i.e. 1:3
8-3:1 # i.e. 5:7
12-3:1 # i.e. 9:11
16-4:1 # i.e. 13:15
SOLUTION: always parenthesize arguments to :
if they involve arithmetic or are expressions: a[(i-3):i]