How to insert an element at a specific position of an empty vector?

Viewed 152

In R we can create an empty vector where it is possible to insert an element in any position of this vector. Example:

> x <- c()
> x[1] = 10
> x[4] = 20

The final result is:

> x
[1] 10 NA NA 20

I would like to do something similar using Julia, but couldn't find a way to do this. The “append” function do not perform something like that.

Could anyone help?

1 Answers

You need to do this in two steps:

  1. First resize the vector or create a vector with an appropriate size.
  2. Next set the elements accordingly.

Since you are coming from R I assume you want the vector to be initially filled with missing values. Here is the way to do this.

In my example I assume you want to store integers in the vector. Before both options load the Missings.jl package:

using Missings

Option 1. Start with an empty vector

julia> x = missings(Int, 0)
Union{Missing, Int64}[]

julia> resize!(x, 4)
4-element Vector{Union{Missing, Int64}}:
 missing
 missing
 missing
 missing

julia> x[1] = 10
10

julia> x[4] = 40
40

julia> x
4-element Vector{Union{Missing, Int64}}:
 10
   missing
   missing
 40

Option 2. Preallocate a vector

julia> x = missings(Int, 4)
4-element Vector{Union{Missing, Int64}}:
 missing
 missing
 missing
 missing

julia> x[1] = 10
10

julia> x[4] = 40
40

The reason why Julia does not resize the vectors automatically is for safety. Sometimes it would be useful, but most of the time if x is an empty vector and you write x[4] = 40 it is a bug in the code and Julia catches such cases.


EDIT

What you can do is:

function setvalue(vec::Vector, idx, val)
    @assert idx > 0
    if idx > length(vec)
        resize!(vec, idx)
    end
    vec[idx] = val
    return vec
end
Related