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
A vector in Julia can be represented by its individual components, but it is more convenient to combine them into a collection using the [,] notation: The basic vector operations are implemented for vector objects. For example, the vector v has scalar multiplication defined for it: The norm function returns the magnitude of the vector (by default):
It also supports many custom types to take more advantage. In order to provide consistency between some predefined types for missing values and some custom types, Julia introduces new missing object, an object having no fields which are the only instance of the Missing singleton type. Values can be either of type T or missing.
To compute the average of vector elements, Julia provides a predefined function mean () to calculate the average of elements. Vector addition uses ‘+’ and vector subtraction uses ‘ -‘.
In practice, this means a math operation involving a missing value generally returns missing: Since missing is a normal Julia object, this propagation rule only works for functions which have opted in to implement this behavior. This can be achieved by: adding a specific method defined for arguments of type Missing,
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 Missing
s:
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
Vector{Union{Float64,Missing}}(missing, 5)
should do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With