Strange behavior when updating a sub array with lag function using ShiftedArrays

Viewed 58

When I try to update a sub array of a vector with the lagged one, the result is a bit strange, is it the expected behavior?

MWE:

using ShiftedArrays
x = [1,2,3,4,missing];
y = lag(view(x, 2:3));
x[2:3] = y;
 x
5-element Vector{Union{Missing, Int64}}:
 1
  missing
  missing
 4
  missing

x[2:3] are both missing.

1 Answers

this is because y is lag of a view, so when you update the x[2:3], first it sets x[2] to missing, because that's the first element of y, but that makes the second element of y missing as well. (originally, the second element of y is 2). So by the time it sets x[3], it's missing too.

you need to make a copy somewhere, or update the array in reverse order.

btw, your code isn't doing much, if you simply want to lag by 1 and insert a missing somewhere, you can simply insert it:


julia> x[2:3] .= missing, x[2]

julia> x
5-element Vector{Union{Missing, Int64}}:
 1
  missing
 2
 4
  missing
Related