# Is there a sparse array with 'missing' as default

**URL:** <https://discourse.julialang.org/t/is-there-a-sparse-array-with-missing-as-default/122095>\
**Category:** General Usage\
**Tags:** question\
**Created:** [October 31, 2024, 7:25pm UTC](https://discourse.julialang.org/t/is-there-a-sparse-array-with-missing-as-default/122095 "2024-10-31T19:25:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![feanor12](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/feanor12/32/8212_2.png) [@feanor12](https://discourse.julialang.org/u/feanor12)\
**Post date:** [October 31, 2024, 7:25pm UTC](https://discourse.julialang.org/t/is-there-a-sparse-array-with-missing-as-default/122095/1 "2024-10-31T19:25:46Z")

</div>

something like :

`[missing,1.5,missing,missing]`

where only `2 => 1.5` is stored?

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [October 31, 2024, 10:26pm UTC](https://discourse.julialang.org/t/is-there-a-sparse-array-with-missing-as-default/122095/2 "2024-10-31T22:26:58Z")

</div>

Depending on your needs, `get` could work well for you here:

```julia-repl
julia> d = Dict{Int,Float64}(2 => 1.5)
Dict{Int64, Float64} with 1 entry:
  2 => 1.5

julia> get(d, 1, missing)
missing

julia> get(d, 2, missing)
1.5

julia> get(d, 3, missing)
missing

```

If you want this wrapped in an `AbstractArray`, then you can implement an [array interface](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array) wrapper for it. Like this:

```julia
struct SparseFillArray{T, U, D} <: AbstractArray{Union{T, U}, D}
	dat::Dict{Int, T}
	fillval::U
	sz::NTuple{D, Int}
end

Base.IndexStyle(::Type{<:SparseFillArray}) = IndexLinear()

Base.size(A::SparseFillArray) = A.sz

function Base.getindex(A::SparseFillArray, i::Int)
	1 <= i <= length(A) || Base.throw_boundserror(A, (i,))
	return get(A.dat, i, A.fillval)
end

function Base.setindex!(A::SparseFillArray, val, i::Int)
	1 <= i <= length(A) || Base.throw_boundserror(A, (i,))
	if isequal(A.fillval, val)
		delete!(A.dat, i)
	else
		A.dat[i] = val
	end
	return val
end

```

```julia-repl
julia> x = SparseFillArray(Dict{Int, Float64}(), missing, (3,3))
3×3 SparseFillArray{Float64, Missing, 2}:
 missing missing missing
 missing missing missing
 missing missing missing

julia> x[2,1] = 1.5
1.5

julia> x
3×3 SparseFillArray{Float64, Missing, 2}:
  missing missing missing
 1.5 missing missing
  missing missing missing

julia> x.dat
Dict{Int64, Float64} with 1 entry:
  2 => 1.5

```

You could hardcode the fillval to be `missing`, but here I kept it general.
