Struct
Constructors are functions that create new objects. In Julia, constructors can also be used as functions when applied to an argument tuple. This can be done using struct
syntax. struct
is a kind of type in Julia that is specified as a name and a set of fields. It looks similar to JSON
representation without specific values assigned.
struct Foo
bar
baz
end
# Note that when Foo is served as a constructor function,
# each element of the argument tuple is used as a value for the ordered fields.
foo = Foo("happy","bear")
foo.bar
julia> "happy"
foo.baz
julia> "bear"
# Order matters
foo = Foo("bear","happy?")
foo.bar
julia> "bear"
foo.baz
julia> "happy?"
For loop
Creating a for loop in Julia is straightforward.The following codes will iterate over i = 1,2,3,…, 10 and print the number.
for i in 1:10
println(i)
end
RData
Performing simulations to find convergence using R could take a very long time. To speed things up, we want to use Julia for simulations. To do so, we load R object using RData
package in Julia and use it as inputs for simulation. Follow these steps:
using RData
import CodeBZip2
# objs will be Dictionary
objs=load('data/pr_a2.rda')
print(objs)
julia>
Dict{String, Any} with 1 entry:
"pr_a2" => 9×7 DataFrame…
# extract the object to store it as a dataframe
pr_a2=objs["pr_a2"]
julia>
9×7 DataFrame
Filter in DataFrame
To filter rows in a data frame, use filter(source => f::Function, df)
. The following example demonstrates filtering rows in the pr_a2
data frame using var1
and var2
to satisfy two conditions: (1) var1==s0
, (2) var2==g0
. Note that each row in var1
and var2
is denoted as s
and g
, respectively. The code would look like this:
# for each element in the column var1 and var2,
# where each element for respective column is represented by s and g,
# find rows in pr_a2 that makes s equals s0 and g equals g0
# then return column var3
filter([:var1, :var2]=>
(s,g)->s==s0 && g==g0, pr_a2)[:var3]
Sample
Suppose I want to generate 10 random values from a set [“a”, “b”], where “a” has a probabiility of 0.3 and “b” has a probability of 0.7. This means that the probability of drawing “a” is 0.3, and the probability of drawing “b” is 0.7. I can use wsample
to perform the task.
wsample(["a", "b"], [0.3, 0.7], 10)
julia>
10-element Vector{String}:
"b"
"b"
"b"
"b"
"a"
"a"
"b"
"b"
"a"
"b"
Reference
struct
: https://docs.julialang.org/en/v1/manual/constructors/
RData
: https://github.com/JuliaData/RData.jl
filter
: https://juliadatascience.io/filter_subset
wsample
: https://juliastats.org/StatsBase.jl/stable/sampling/