println(5 + 5)
println(5 * 5)
println(sqrt(5))
println(√(5))
println(5 / 2)
println(5 ÷ 2)
println(5 % 2)
println(5 // 10)
println(1 // 2 * 5 // 10) # BTW: comments can be written using #
10 25 2.23606797749979 2.23606797749979 2.5 2 1 1//2 1//4
Variables are assigned with =
.
x = [1, 2, 4, 55]
4-element Vector{Int64}: 1 2 4 55
Notice how the vector was still printed even though we were just assigning a value? We can prevent this behvaior by appending a function call with ;
.
x = [1, 2, 4, 55];
x
4-element Vector{Int64}: 1 2 4 55
We can assign variables to unicode representations!
β̂₀ = 5.1; # \beta\hat\_0 followed by a tab
β̂₀
5.1
Groups of items are stored in arrays, tuples, and dictionaries. Arrays are created with [
and tuples with (
.
z = [1, 2, 3, 4];
w = (1, 2, 3, 4);
z
4-element Vector{Int64}: 1 2 3 4
w
(1, 2, 3, 4)
The difference between and array and a tuple is that tuples are immutable (they can't be changed once created).
push!(z, 5)
5-element Vector{Int64}: 1 2 3 4 5
push!(w, 5)
MethodError: no method matching push!(::NTuple{4, Int64}, ::Int64) Closest candidates are: push!(::Any, ::Any, ::Any) at abstractarray.jl:2387 push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388 push!(::AbstractChannel, ::Any) at channels.jl:10 ... Stacktrace: [1] top-level scope @ In[12]:1 [2] eval @ ./boot.jl:360 [inlined] [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String) @ Base ./loading.jl:1094
z
, is the equivalent of c(1, 2, 3, 4)
in R. With the ,
we create a vector. If we omit it we create a matrix.
[1 2 3 4]
1×4 Matrix{Int64}: 1 2 3 4
[1 2 3 4; 5 6 7 8]
2×4 Matrix{Int64}: 1 2 3 4 5 6 7 8
Arrays are indexed starting at 1.
z[1]
1
z[2:end]
4-element Vector{Int64}: 2 3 4 5
z[begin:end-1]
4-element Vector{Int64}: 1 2 3 4
Shell mode is entered by first type ;
. We can then directly interact with the terminal. No more multiple windows!
;pwd
/Users/Nick/Desktop/julia-computing-club
;git status
fatal: not a git repository (or any of the parent directories): .git
Pkg
mode can be entered by typing ]
in the REPL. Package mode is where you add/manage Julia packages as well as project environments. Julia comes with the ability to work in projects with distinct package environments. This is allows us to share a project with others and not worry about package versions, etc. To activate a project:
]activate .
To add a package we use the add
command followed by the name of the project:
]add RCall
What if we wanted to share a project with someone?
;ls
JULIA IS THE FUTURE.ipynb Manifest.toml Project.toml
Notice that 2 files we're created when I added a package after calling activate
, Manifest.toml and Project.toml. These .toml files contain the information about the state of the project.
;cat Manifest.toml
# This file is machine-generated - editing it directly is not advised [[ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" [[Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[CategoricalArrays]] deps = ["DataAPI", "Future", "JSON", "Missings", "Printf", "Statistics", "StructTypes", "Unicode"] git-tree-sha1 = "18d7f3e82c1a80dd38c16453b8fd3f0a7db92f23" uuid = "324d7699-5711-5eae-9e2f-1d82baa6b597" version = "0.9.7" [[ChainRulesCore]] deps = ["Compat", "LinearAlgebra", "SparseArrays"] git-tree-sha1 = "b391f22252b8754f4440de1f37ece49d8a7314bb" uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" version = "0.9.44" [[Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "e4e2b39db08f967cc1360951f01e8a75ec441cab" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.30.0" [[CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" [[Conda]] deps = ["JSON", "VersionParsing"] git-tree-sha1 = "299304989a5e6473d985212c28928899c74e9421" uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d" version = "1.5.2" [[Crayons]] git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d" uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" version = "4.0.4" [[DataAPI]] git-tree-sha1 = "dfb3b7e89e395be1e25c2ad6d7690dc29cc53b1d" uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" version = "1.6.0" [[DataFrames]] deps = ["Compat", "DataAPI", "Future", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrettyTables", "Printf", "REPL", "Reexport", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] git-tree-sha1 = "66ee4fe515a9294a8836ef18eea7239c6ac3db5e" uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" version = "1.1.1" [[DataStructures]] deps = ["Compat", "InteractiveUtils", "OrderedCollections"] git-tree-sha1 = "4437b64df1e0adccc3e5d1adbc3ac741095e4677" uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" version = "0.18.9" [[DataValueInterfaces]] git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" version = "1.0.0" [[Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[DelimitedFiles]] deps = ["Mmap"] uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" [[Distributed]] deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[DocStringExtensions]] deps = ["LibGit2", "Markdown", "Pkg", "Test"] git-tree-sha1 = "9d4f64f79012636741cf01133158a54b24924c32" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.8.4" [[Downloads]] deps = ["ArgTools", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" [[Formatting]] deps = ["Printf"] git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8" uuid = "59287772-0a20-5a39-b81b-1366585eb4c0" version = "0.4.2" [[Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[InvertedIndices]] deps = ["Test"] git-tree-sha1 = "15732c475062348b0165684ffe28e85ea8396afc" uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" version = "1.0.0" [[IteratorInterfaceExtensions]] git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" uuid = "82899510-4779-5014-852e-03e436cf321d" version = "1.0.0" [[JLLWrappers]] deps = ["Preferences"] git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.3.0" [[JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "81690084b6198a2e1da36fcfda16eeca9f9f24e4" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.1" [[LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" [[LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" [[LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" [[Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[LinearAlgebra]] deps = ["Libdl"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[LogExpFunctions]] deps = ["DocStringExtensions", "LinearAlgebra"] git-tree-sha1 = "1ba664552f1ef15325e68dc4c05c3ef8c2d5d885" uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" version = "0.2.4" [[Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" [[Missings]] deps = ["DataAPI"] git-tree-sha1 = "4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7" uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" version = "1.0.0" [[Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" [[NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" [[OpenSpecFun_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "b9b8b8ed236998f91143938a760c2112dceeb2b4" uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" version = "0.5.4+0" [[OrderedCollections]] git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.4.1" [[Parsers]] deps = ["Dates"] git-tree-sha1 = "c8abc88faa3f7a3950832ac5d6e690881590d6dc" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "1.1.0" [[Pkg]] deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" [[PooledArrays]] deps = ["DataAPI", "Future"] git-tree-sha1 = "cde4ce9d6f33219465b55162811d8de8139c0414" uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" version = "1.2.1" [[Preferences]] deps = ["TOML"] git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.2.2" [[PrettyTables]] deps = ["Crayons", "Formatting", "Markdown", "Reexport", "Tables"] git-tree-sha1 = "b60494adf99652d220cdef46f8a32232182cc22d" uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" version = "1.0.1" [[Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[RCall]] deps = ["CategoricalArrays", "Conda", "DataFrames", "DataStructures", "Dates", "Libdl", "Missings", "REPL", "Random", "Requires", "StatsModels", "WinReg"] git-tree-sha1 = "5108a75602f6a11f7737707dff26461ef02abc66" uuid = "6f49c342-dc21-5d91-9882-a32aef131414" version = "0.13.11" [[REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[Random]] deps = ["Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[Reexport]] git-tree-sha1 = "57d8440b0c7d98fc4f889e478e80f268d534c9d5" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.0.0" [[Requires]] deps = ["UUIDs"] git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.1.3" [[Rmath]] deps = ["Random", "Rmath_jll"] git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f" uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa" version = "0.7.0" [[Rmath_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7" uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f" version = "0.3.0+0" [[SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" [[Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[ShiftedArrays]] git-tree-sha1 = "22395afdcf37d6709a5a0766cc4a5ca52cb85ea0" uuid = "1277b4bf-5013-50f5-be3d-901d8477a67a" version = "1.0.0" [[Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[SortingAlgorithms]] deps = ["DataStructures"] git-tree-sha1 = "2ec1962eba973f383239da22e75218565c390a96" uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" version = "1.0.0" [[SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[SpecialFunctions]] deps = ["ChainRulesCore", "LogExpFunctions", "OpenSpecFun_jll"] git-tree-sha1 = "c467f25b6ec4167ea3a9a4351c66c2e1cba5da33" uuid = "276daf66-3868-5448-9aa4-cd146d93841b" version = "1.4.1" [[Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[StatsAPI]] git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510" uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" version = "1.0.0" [[StatsBase]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] git-tree-sha1 = "2f6792d523d7448bbe2fec99eca9218f06cc746d" uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" version = "0.33.8" [[StatsFuns]] deps = ["LogExpFunctions", "Rmath", "SpecialFunctions"] git-tree-sha1 = "30cd8c360c54081f806b1ee14d2eecbef3c04c49" uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c" version = "0.9.8" [[StatsModels]] deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Printf", "ShiftedArrays", "SparseArrays", "StatsBase", "StatsFuns", "Tables"] git-tree-sha1 = "0bac85a98ffc5b81503b49004517ee83f12f0ef6" uuid = "3eaba693-59b7-5ba5-a881-562e759f1c8d" version = "0.6.22" [[StructTypes]] deps = ["Dates", "UUIDs"] git-tree-sha1 = "e36adc471280e8b346ea24c5c87ba0571204be7a" uuid = "856f2bd8-1eba-4b0a-8007-ebc267875bd4" version = "1.7.2" [[TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [[TableTraits]] deps = ["IteratorInterfaceExtensions"] git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" version = "1.0.1" [[Tables]] deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"] git-tree-sha1 = "c9d2d262e9a327be1f35844df25fe4561d258dc9" uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" version = "1.4.2" [[Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" [[Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[VersionParsing]] git-tree-sha1 = "80229be1f670524750d905f8fc8148e5a8c4537f" uuid = "81def892-9a0e-5fdd-b105-ffc91e053289" version = "1.2.0" [[WinReg]] deps = ["Test"] git-tree-sha1 = "808380e0a0483e134081cc54150be4177959b5f4" uuid = "1b915085-20d7-51cf-bf83-8f477d6f5128" version = "0.3.1" [[Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" [[nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" [[p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
If I were to share this project with a collaborator, they would run:
;activate .
;instantiate
Similarly to R, we can access Julia documentation with ?
. This tells Julia to enter Help
mode. Let's look at the documentation for the mean
function.
?mean
search: SegmentationFault macroexpand @macroexpand @macroexpand1 Meta numerator Couldn't find mean Perhaps you meant map, max, min, atan, read, real, tan, Real, Meta or merge
No documentation found.
Binding mean
does not exist.
We receive a message that the "Binding mean
does not exist." This is because the mean
function is part of the Statistics.jl package. To load the package we use using
.
using Statistics
?mean
search: mean mean! median median! SegmentationFault macroexpand @macroexpand
mean(itr)
Compute the mean of all elements in a collection.
!!! note
If itr
contains NaN
or missing
values, the result is also NaN
or missing
(missing
takes precedence if array contains both). Use the skipmissing
function to omit missing
entries and compute the mean of non-missing values.
jldoctest
julia> using Statistics
julia> mean(1:20)
10.5
julia> mean([1, missing, 3])
missing
julia> mean(skipmissing([1, missing, 3]))
2.0
mean(f::Function, itr)
Apply the function f
to each element of collection itr
and take the mean.
jldoctest
julia> using Statistics
julia> mean(√, [1, 2, 3])
1.3820881233139908
julia> mean([√1, √2, √3])
1.3820881233139908
mean(f::Function, A::AbstractArray; dims)
Apply the function f
to each element of array A
and take the mean over dimensions dims
.
!!! compat "Julia 1.3" This method requires at least Julia 1.3.
jldoctest
julia> using Statistics
julia> mean(√, [1, 2, 3])
1.3820881233139908
julia> mean([√1, √2, √3])
1.3820881233139908
julia> mean(√, [1 2 3; 4 5 6], dims=2)
2×1 Matrix{Float64}:
1.3820881233139908
2.2285192400943226
mean(A::AbstractArray; dims)
Compute the mean of an array over the given dimensions.
!!! compat "Julia 1.1"
mean
for empty arrays requires at least Julia 1.1.
jldoctest
julia> using Statistics
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> mean(A, dims=1)
1×2 Matrix{Float64}:
2.0 3.0
julia> mean(A, dims=2)
2×1 Matrix{Float64}:
1.5
3.5
I didn't have to add the Statistics package because it's part of the base ecosystem for Julia. However, unlike R, this package is automatically loaded when starting a Julia session.
From the Julia wiki: "A function is a collected group of instructions that can return one or more values, possibly based on the input arguments..." Just like in R, a function maps an input to an output.
mean(x)
15.5
Functions are defined with the function
keyword.
function helloworld(x)
println("Hello, " * x)
end
helloworld("Computing Club!")
Hello, Computing Club!
Notice that the function scope is closed with the end
keyword. This is in contrast to R which use {}
or Python which uses tabs (ew...). There is also function definition shorthand we can use.
helloworld(x) = println("Hello, " * x)
helloworld (generic function with 1 method)
helloworld("Nick!")
Hello, Nick!
Anonymous functions can be defined using the ->
syntax.
x -> println("Hello, " * x)
#1 (generic function with 1 method)
Functions can have multiple methods where the methods performs a specific job based on the types of the function arguments.
function helloworld(x::String)
println("Hello, " * x)
end
helloworld("Computing club!")
Hello, Computing club!
What happens if we pass in a number instead of a string?
helloworld(5)
MethodError: no method matching *(::String, ::Int64) Closest candidates are: *(::Any, ::Any, ::Any, ::Any...) at operators.jl:560 *(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at int.jl:88 *(::Union{AbstractChar, AbstractString}, ::Union{AbstractChar, AbstractString}...) at strings/basic.jl:260 ... Stacktrace: [1] helloworld(x::Int64) @ Main ./In[29]:1 [2] top-level scope @ In[33]:1 [3] eval @ ./boot.jl:360 [inlined] [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String) @ Base ./loading.jl:1094
function helloworld(x::Number)
println("Why would I say hello to a number!")
end
helloworld(5)
Why would I say hello to a number!
function helloworld(x::String, y::Number)
println("Hello, " * x^y)
end
helloworld("Nick ", 4)
Hello, Nick Nick Nick Nick
This is multiple dispatch! Based on the types of the arguments passed to the method Julia decides how to properly execute the function. It's called multiple dispatch because the dispatching can occur on multiple argument types. Contrast this with the S3 system in R where the method can only be decided on using the class of the first argument. We can see all the different methods associated with a function with methods
.
methods(helloworld)
[2, 3, 4, 5] ^ 2
MethodError: no method matching ^(::Vector{Int64}, ::Int64) Closest candidates are: ^(::Union{AbstractChar, AbstractString}, ::Integer) at strings/basic.jl:718 ^(::LinearAlgebra.Symmetric{var"#s832", S} where {var"#s832"<:Real, S<:(AbstractMatrix{var"#s832"} where var"#s832"<:var"#s832")}, ::Integer) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/symmetric.jl:868 ^(::LinearAlgebra.Symmetric{var"#s832", S} where {var"#s832"<:Complex, S<:(AbstractMatrix{var"#s832"} where var"#s832"<:var"#s832")}, ::Integer) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.6/LinearAlgebra/src/symmetric.jl:869 ... Stacktrace: [1] macro expansion @ ./none:0 [inlined] [2] literal_pow(f::typeof(^), x::Vector{Int64}, #unused#::Val{2}) @ Base ./none:0 [3] top-level scope @ In[37]:1 [4] eval @ ./boot.jl:360 [inlined] [5] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String) @ Base ./loading.jl:1094
We can create a for loop using the for
keyword.
answer = []
for x in [2, 3, 4, 5]
push!(answer, x^2)
end
answer
4-element Vector{Any}: 4 9 16 25
Julia also makes use of list comprehension.
[x^2 for x in [2, 3, 4, 5]]
4-element Vector{Int64}: 4 9 16 25
There's also a map.
map(x -> x^2, [2, 3, 4, 5]) # notice the use of the anonymous function
4-element Vector{Int64}: 4 9 16 25
Another option is called broadcasting. We can broadcast any function by appending the function name with .
. If the function is an operator, then we add .
to the beginning of the operator.
[2, 3, 4, 5] .^ 2
4-element Vector{Int64}: 4 9 16 25
struct Person
name::String
age::Int
occupation::String
end
nick = Person("Nick", 25, "Biostatistician")
Person("Nick", 25, "Biostatistician")
typeof(nick)
Person
nick.age
25
Base.show(io::IO, t::Person) = print(io, t.name * " is a " * t.occupation)
nick
Nick is a Biostatistician
We can use R within Julia with the RCall package. This is also possible with Python, MATLAB, Mathmatica.
using RCall
┌────────────────────────────────────────────────┐ │ │ │ Welcome back, Nick! │ │ Today's date and time: 2021-05-25 13:43:37 │ │ │ └────────────────────────────────────────────────┘
R"""
summary(lm(mpg ~ cyl, data = mtcars))
"""
RObject{VecSxp} Call: lm(formula = mpg ~ cyl, data = mtcars) Residuals: Min 1Q Median 3Q Max -4.9814 -2.1185 0.2217 1.0717 7.5186 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 37.8846 2.0738 18.27 < 2e-16 *** cyl -2.8758 0.3224 -8.92 6.11e-10 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 3.206 on 30 degrees of freedom Multiple R-squared: 0.7262, Adjusted R-squared: 0.7171 F-statistic: 79.56 on 1 and 30 DF, p-value: 6.113e-10
rcopy(R"rnorm(10)")
10-element Vector{Float64}: 0.4860451724519105 -1.690549789770062 0.5595315478840313 2.5779042701739576 0.12649264379668596 -0.7805743892870097 -0.028167339151651098 -1.0900738592461838 0.044868981029354674 0.30939258436096195