Template [Julia]
1. Data types, data structures and indexing
1.1 Basics
Object, assignment, functions, how to comment and get help
# We can use Julia as a calculator!# Functions help us execute things; we usually have to provide arguments# Don't know how a function works? Ask for help1.2 Data types
Numeric (integers or doubles)
String
Boolean
1.3 Data classes
Arrays
Arrays are ordered collection of elements.
A 1-dimensional array is a vector.
What happens when we add 1 to a logical vector?
In Julia, arrays can contain elements of different types.
A 2-dimensional array is a matrix.
reshape(my_vector, (lines, columns)) # reshapes my_vectorArrays can also contain other arrays.
Tuples
(name_element1 = element1, name_element2 = element2, name_element3 = element3)Data frames
DataFrame(vector1, vector2) # bind vectors with the same length1.4 Dimensions
size(matrix) # returns the dimensionslength(object) # returns the number of elementsCan you guess the value of the length of my_array_of_arrays?
size(my_array_of_arrays)length(my_array_of_arrays)1.5 Indexing
# 1-dimensionalvector[index]# 2-dimensionalmatrix[row, column]dataframe[row, column]# Multi-dimensionalarray[element][...]tuple[element][...]1.6 Slicing
2. Files
Absolute paths
C:/Users/RonBumblefootThal/Documents/RFolder/MyFirstProject/Draft/IDon'tKnowWhatI'mDoing/etc.R
Relative Paths
~/I_love_my_project/CoolCode.R
2.1 Working directories
2.2 Save/write files
Save a dataframe
soa_tour = DataFrame(country = ["USA", "UK", "FRA", "GER", "BRA"], frequency = [34, 9, 6, 5, 3], continents = ["north_america", "europe", "europe", "europe", "south_america"])# Function structureCSV.write(path, object)2.3 Load/read files
From your PC
object = CSV.read(path)From url to your PC, then read
download("http://remote.repo/data/file.csv", path)object = CSV.read(path)Metabolic rates data: http://sciencecomputing.io/data/metabolicrates.csv
3. Control Flow
You already apply control flow when you decide how to go to work during winter.
For example:
You take the metro if it's snowy
You take the metro if it's cold
You walk every other time
Now, let's put that into code!
3.1 Conditional evaluation
Simple if statement
Structure:
if (condition is true) do expressionendExample:
If/else statement
Structure:
if (condition) expression 1else expression 2endExample:
Nested if /else statement
if (condition 1) expression 1 if (condition 2) expression 2 endendExample:
Simpler alternative:
Adding a condition:
3.2 For loops
Simple for loops
Using for loops, you can then plan your schedule for a few days.
What we had:
weather = "snowy"temperature = -15But what about this?
weather_vec = ["snowy", "cloudy", "snowy", "clear", "rainy"]temperature_vec = [-15, -23, -2, -40, 5]Does the same code work?
if weather_vec == "snowy" || temperature_vec < -20 println("Take the metro!")else println("Let's walk!")endIterations
for i in iterations expression(i)endMore generally:
If statement inside for loops
Structure:
for i in iterations if (condition) expression1 else expression2 endendExample:
# Previous statementif weather_vec == "snowy" || temperature_vec < -20 println("Take the metro!")else println("Let's walk!")end# Will this work? # Previous statement if weather_vec == "snowy" || temperature_vec < -20 println("Take the metro!") else println("Let's walk!") end3.3 Extras
Some logical operators
Comparisons:
less than (
<)more than (
>)less than or equal to (
<=)more than or equal to (
>=)equal to (
==)not equal to (
!=)
Logic:
not x (
!x)x or y (
x || y)x and y (
x && y)
4. Functions
4.1 Syntax and arguments
Basic syntax
function functionname(argument1, argument2) # Name and arguments result = expression # What the function does return result # What the function returnsend# Define a function# Apply on values# Apply on variablesCalling (personal) functions within functions
4.2 Scope
Variables can exist either in global or local scope.
Remember, the element to return in our function was called abs_result.
# What will this return, outside the function?resultHere is a second example for ecologists who like to count living things:
# Global variables4.3 Integration
Combining functions and control flow
Let's come back to our previous example about transportation according to the weather.
Here is the forecast for the week and the weekend:
# Week forecastweather_week = ["snowy", "cloudy", "snowy", "clear", "rainy"]temperature_week = [-15.0, -23.0, -2.0, -40.0, 5.0]# Weekend forecastweather_weekend = ["snowy", "rainy"]temperature_weekend = [-3.0, 2.0]Now, let's build a function that will work with either the week or weekend forecasts.
It will look like:
function transportation for all days of the week/weekend if (snowy or cold) take metro else walk end endend# Create a new function # Previous for loop for i in 1:length(weather_vec) if weather_vec[i] == "snowy" || temperature_vec[i] < -15.0 println("Take the metro") else println("Just walk") end end# Plan for the week# Plan for the weekend4.4 Exercise - Planning the week
Exercise to integrate the following:
Functions
Control flow
Files
Write a function to read a file if it exists, downloading it first if it does not exist.
Apply the
choose_transportationfunction to the data in the file
# Pseudocodefunction (file, url) if (file exists) read file else download file read fileend# Useful functions?isfile?CSV.read?downloadForecast data url: https://docs.google.com/spreadsheets/d/e/2PACX-1vSdqGDzfGPygowYRaffMTsVHQz1nejPPyjE2Q1yYIRKPUfhayMTcCMhdzqfbea5IeYKi82aW4NDas_G/pub?gid=0&single=true&output=csv4.5 Extras
Default values
# Define functionfunction add_and_multiply(var1, var2; var3 = 1) result = (var1 + var2) * var3 return resultendadd_and_multiply(1.0, 2.0) # multiplies by 1, as defaultadd_and_multiply(1.0, 2.0, 2.0) # returns erroradd_and_multiply(1.0, 2.0, var3 = 2.0) # proper syntaxControlling return
function add_and_multiply(var1, var2; var3 = 1) addition_result = var1 + var2 multiplication_result = addition_result * var3 return (added = addition_result, multiplied = multiplication_result)end