Skip to content
This repository was archived by the owner on May 4, 2019. It is now read-only.

Allow replacing with results of a function #176

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/abstractdataarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,13 @@ type EachReplaceNA{S, T}
replacement::T
end
function each_replacena(da::AbstractDataArray, replacement::Any)
if isa(replacement, Function)
EachReplaceNAWithFunctionResult(da, replacement)
else
EachReplaceNA(da, convert(eltype(da), replacement))
end
end

function each_replacena(replacement::Any)
x -> each_replacena(x, replacement)
end
Expand All @@ -167,4 +172,16 @@ Base.done(itr::EachReplaceNA, ind::Integer) = ind > length(itr.da)
function Base.next(itr::EachReplaceNA, ind::Integer)
item = isna(itr.da, ind) ? itr.replacement : itr.da[ind]
(item, ind + 1)
end
end

type EachReplaceNAWithFunctionResult{T}
da::AbstractDataArray{T}
f::Function
end

Base.start(itr::EachReplaceNAWithFunctionResult) = 1
Base.done(itr::EachReplaceNAWithFunctionResult, ind::Int) = ind > length(itr.da)
function Base.next(itr::EachReplaceNAWithFunctionResult, ind::Integer)
item = isna(itr.da, ind) ? itr.f(itr.da) : itr.da[ind]
(item, ind + 1)
end
5 changes: 5 additions & 0 deletions test/nas.jl
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,9 @@ module TestNAs
@test_throws NAException for v in each_failna(dv); end
@test collect(each_dropna(dv)) == a
@test collect(each_replacena(dv, 4)) == [4, 4, a..., 4]

dv = DataArray(Array(1:6), push!(fill(false, 3),fill(true, 3)...))
a = dropna(dv)
f = x -> round(Int, mean(dropna(x)))
@test collect(each_replacena(dv, f)) == [1, 2, 3, 2, 2, 2]
end