Equivalent to R's dput in Julia
Asked Answered
K

3

5

Is there a way to convert an object in Julia to a code representation generating the same object? I am basically looking for an equivalent to R's dput function.

So if I have an object like:

A = rand(2,2)
# Which outputs
>2×2 Array{Float64,2}:
 0.0462887  0.365109
 0.698356   0.302478

I can do something like dput(A) which prints something like the following to the console that can be copy-pasted to be able to replicate the object:

[0.0462887  0.365109; 0.698356   0.302478]
Kr answered 8/7, 2018 at 16:40 Comment(0)
B
6

I think you are looking for repr:

julia> A = rand(2, 2);

julia> repr(A)
"[0.427705 0.0971806; 0.395074 0.168961]"
Bestride answered 9/7, 2018 at 16:52 Comment(0)
S
2

Just use Base.dump.

julia> dump(rand(2,2))
Array{Float64}((2, 2)) [0.162861 0.434463; 0.0823066 0.519742] 

You can copy the second part.

Supposal answered 8/7, 2018 at 16:50 Comment(2)
Hi L Woo. Thanks for this. It doesnt work in larger cases though. For instance if we try to dump(rand(6,6)) a bunch of the numbers are replaced by ... so you cannot replicate the object.Kr
With dump you can use dump(IOContext(STDOUT, :limit => false), rand(6,6)). Of course the representation is only approximate and you have to discard the first part of the generated expression.Kurland
L
0

(This is a modified crosspost of https://mcmap.net/q/1461840/-how-to-provide-reproducible-sample-data-in-julia)

repr might not work as expected for DataFrames. Here is one way to mimic the behaviour of R's dput for DataFrames in Julia:

julia> using DataFrames

julia> using Random; Random.seed!(0);

julia> df = DataFrame(a = rand(3), b = rand(1:10, 3))
3×2 DataFrame
 Row │ a          b
     │ Float64    Int64
─────┼──────────────────
   1 │ 0.405699       1
   2 │ 0.0685458      7
   3 │ 0.862141       2

julia> repr(df) # Attempting with repr()
"3×2 DataFrame\n Row │ a          b\n     │ Float64    Int64\n─────┼──────────────────\n   1 │ 0.405699       1\n   2 │ 0.0685458      7\n   3 │ 0.862141       2"

julia> julian_dput(x) = invoke(show, Tuple{typeof(stdout), Any}, stdout, df);

julia> julian_dput(df)
DataFrame(AbstractVector[[0.4056994708920292, 0.06854582438651502, 0.8621408571954849], [1, 7, 2]], DataFrames.Index(Dict(:a => 1, :b => 2), [:a, :b]))

That is, julian_dput() takes a DataFrame as input and returns a string that can generate the input.

Source: https://discourse.julialang.org/t/given-an-object-return-julia-code-that-defines-the-object/80579/12

Latimore answered 15/8, 2022 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.