How to make a function recognize datatype argument

Here is a function that is supposed to turn a vector of strings to an Array{Union{Missing,Int64}:

function NAtoMissing(data::Array{Any,1},nonmissing::DataType,tomissing::Any)
    withmissing = Array{Union{Missing, nonmissing},1}(missing,length(data))
    for i = 1:length(data)
        if data[i] == tomissing
            withmissing[i] = missing
        else
            withmissing[i] = parse(nonmissing,data[i])
        end
    end
    withmissing
end

test = ["1", "2", "NA"]
NAtoMissing(test,Int64,"NA")

Output:

MethodError: no method matching NAtoMissing(::Array{String,1}, ::Type{Int64}, ::String)
Closest candidates are:
  NAtoMissing(!Matched::Array{Any,1}, ::DataType, ::Any) 
....

So it’s complaining that my second argument is not ::DataType, yet:

typeof(Int64) 
DataType

Obviously I’m not reading this correctly…

edit: fixed the update line in function

Misread the error message, the problem was not with the second argument but with the first.
This fixes it: data::Array{Any,1} → data::Array{<: Any,1}

Note that you could write the Array{<:Any, 1} as Vector.

1 Like