umair durrani
umair durrani

Reputation: 6199

How to create a vector of missing values of certain length in julia?

In R I can create a vector length 5 with all NA_real_ values:

x <- 1:5
length(x)
## [1] 5
rep(NA_real_, times = length(x))
## [1] NA NA NA NA NA  

How can I do the same in julia? I can create a vector containing zeros, but I don't know how to put missing values in there:

v = Vector{Float64}(undef, 5)
## 5-element Array{Float64,1}:
 0.0
 0.0
 0.0
 0.0
 0.0

Upvotes: 5

Views: 1050

Answers (2)

PaSTE
PaSTE

Reputation: 4623

The missing value in Julia is called missing. It is a singleton of type Missing. You can create a vector of missing values like this:

v = Vector{Missing}(undef, 5)
# 5-element Array{Missing,1}:
#  missing
#  missing
#  missing
#  missing
#  missing

Or, more conveniently using fill:

v = fill(missing, 5)

Be warned, though, that unlike in R, Missing does not share a type with other numeric types: it is its own type. Notice what happens when you try to put a Float64 into a vector of Missings:

v = fill(missing, 5)
# 5-element Array{Missing,1}:
#  missing
#  missing
#  missing
#  missing
#  missing

v[1] = 3.14
# ERROR: MethodError: convert(::Type{Union{}}, ::Float64) is ambiguous.

This means if you want to create a vector containing only missing values, but you want it to also be able to contain a numeric value like a Float64, you should be explicit:

v = convert(Array{Union{Float64,Missing}}, v)
# 5-element Array{Union{Missing, Float64},1}:
#  missing
#  missing
#  missing
#  missing
#  missing

v[1] = 3.14;
v
# 5-element Array{Union{Missing, Float64},1}:
#  3.14
#   missing
#   missing
#   missing
#   missing

Upvotes: 10

Oscar Smith
Oscar Smith

Reputation: 6398

Vector{Union{Float64,Missing}}(missing, 5) should do what you want.

Upvotes: 4

Related Questions