Reputation: 8117
What a hazzle...
I'm trying to create a vector of integer
s and missing
values. This works fine:
b = [4, missing, missing, 3]
But I would actually like the vector to be longer with more missing
values and therefore use repeat()
, but this doesn't work
append!([1,2,3], repeat([missing], 1000))
and this also doesn't work
[1,2,3, repeat([missing], 1000)]
Please, help me out, here.
Upvotes: 3
Views: 290
Reputation: 69819
It is also worth to note that if you do not need to do an in-place operation with append!
actually in such cases it is much easier to do vertical concatenation:
julia> [[1, 2, 3]; repeat([missing], 2); 4; 5] # note ; that denotes vcat
7-element Array{Union{Missing, Int64},1}:
1
2
3
missing
missing
4
5
julia> vcat([1,2,3], repeat([missing], 2), 4, 5) # this is the same but using a different syntax
7-element Array{Union{Missing, Int64},1}:
1
2
3
missing
missing
4
5
The benefit of vcat
is that it automatically does the type promotion (as opposed to append!
in which case you have to correctly specify the eltype
of the target container before the operation).
Note that because vcat
does automatic type promotion in corner cases you might get a different eltype
of the result of the operation:
julia> x = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
julia> append!(x, [1.0, 2.0]) # conversion from Float64 to Int happens here
5-element Array{Int64,1}:
1
2
3
1
2
julia> [[1, 2, 3]; [1.0, 2.0]] # promotion of Int to Float64 happens in this case
5-element Array{Float64,1}:
1.0
2.0
3.0
1.0
2.0
See also https://docs.julialang.org/en/v1/manual/arrays/#man-array-literals.
Upvotes: 4
Reputation: 42194
This will work:
append!(Union{Int,Missing}[1,2,3], repeat([missing], 1000))
[1,2,3]
creates just a Vector{Int}
and since Julia is strongly typed the Vector{Int}
cannot accept values of non-Int
type. Hence, when defining a structure, that you plan to hold more data types within, you need to explicitly state it - here we have defined Vector{Union{Int,Missing}}
.
Upvotes: 3