Iβm announcing the release of AddToField.jl, a small package with two macros to generate NamedTuples
from blocks of code.
To create NamedTuples
, use @addnt
:
julia> using AddToField;
julia> @addnt begin
@add a = 1
@add b = a + 2
end
(a = 1, b = 3)
julia> @addnt begin
@add "Variable a" a = 1
@add b = a + 2
end
(Variable a = 1, b = 3)
To modify existing structures, use @addto!
julia> D = Dict();
julia> @addto! D begin
@add a = 1
@add b = a + 2
@add "Variable c" c = b + 3
end
Dict{Any,Any} with 3 entries:
:a => 1
:b => 3
Symbol("Variable c") => 6
AddToField makes working with DataFrames easier. First, makes the creation of publication-quality tables easier.
using DataFrames, PrettyTables, Chain
julia> df = DataFrame(
group = repeat(1:2, 50),
income_reported = rand(100),
income_imputed = rand(100));
julia> @chain df begin
groupby(:group)
combine(_; keepkeys = false) do d
@addnt begin
@add "Group" first(d.group)
@add "Mean reported income" m_reported = mean(d.income_reported)
@add "Mean imputed income" m_imputed = mean(d.income_imputed)
@add "Difference" m_reported - m_imputed
end
end
pretty_table(;nosubheader = true)
end
βββββββββ¬βββββββββββββββββββββββ¬ββββββββββββββββββββββ¬βββββββββββββ
β Group β Mean reported income β Mean imputed income β Difference β
βββββββββΌβββββββββββββββββββββββΌββββββββββββββββββββββΌβββββββββββββ€
β 1 β 0.523069 β 0.53696 β -0.0138915 β
β 2 β 0.473178 β 0.41845 β 0.0547277 β
βββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββββ
It also makes constructing data frames easier
julia> using DataFrames
julia> df = DataFrame();
julia> @addto! df begin
x = ["a", "b", "c"]
@add x = x .* "_x"
@add x_y = x .* "_y"
end
3Γ2 DataFrame
Row β x x_y
β String String
ββββββΌββββββββββββββββ
1 β a_x a_x_y
2 β b_x b_x_y
3 β c_x c_x_y
Current limitation
You cannot use @add
in new scopes created with body
. The following will fail
@addnt begin
let
a = 1
@add a
end
end
This is because @addnt
and @addto!
create anonymous variables, then constructs and modifies objects at the end of the block. The same applies for for
loops and function
s inside the @addnt
and @addto!
blocks. In theory, @addto!
should not have this limitation. However I implementing this feature in @addnt
is more complicated, and At the moment maintaining simple feature parity is important.
I have submitted it for registration and should be available for download in 3 days.