# Julia Basics Cheat Sheet

Have this cheat sheet at your fingertips

Download PDF## Accessing help

### Accessing help files and documentation

```
# Access help mode with an empty ?
?
# Get help on a function with ?functionname
?first
# Search for help on a topic with ?topic
?function
```

### Comments

```
# This is a single-line comment
#= This is a
multi-line comment =#
Information about objects
# Get the type of an object with typeof()—The below will return Int64
typeof(20)
```

## Using packages

Packages are libraries of pre-written code (by other programmers) that we can add to our Julia installation, which help us solve specific problems. Here’s how to install and work with packages in Julia.

```
# Enter package mode with ] to be able to install and work with packages in Julia
]
# Install a new package with add
] # Enter package mode
add CSV # Add the CSV package
# Load a package with using
using CSV
# Load a package with import without an alias
import CSV
# Load a package with import with an alias
import DataFrames as df
```

## The working directory

The working directory is a file path that Julia will use as the starting point for relative file paths. That is, it's the default location for importing and exporting files. An example of a working directory looks like ”C://file/path”

```
# Get current working director with pwd()
pwd()
"/home/programming_languages/julia"
# Set the current directory with cd()
cd("/home/programming_languages/julia/cheatsheets")
```

## Operators

### Arithmetic operators

```
# Add two numbers with +
37 + 102
# Substract two numbers with -
102 - 37
# Multiply two numbers with *
4 * 6
# Divide one number with another with /
21/7
# Integer divide one number by another with ÷; keyboard shortcut of \div TAB
22 ÷ 7 # This returns 3
# Inverse divide one number by another with \ — The below is equivalent to 0/5
5 \ 0
# Raise one number to the power of another using ^
3 ^ 3
# Get the remainder after division with a % b
22 % 7
```

### Assignment operators

```
# Assign a value to an object with =
a = 5
# Perform the addition of two objects and store them in the left-hand side object
a += 3 # This is the same as a = a + 3
# Perform the subtraction of two objects and store them in the left-hand side object
a -= 3 # This is the same as a = a - 3
```

### Numeric comparison operators

```
# Test if two objects are equal with ==
3 == 3 # This returns true
# Test if two objects are not equal with !=
3 != 3 # This returns false
# Test if one object is greater than the other
3 > 1
# Test if one object is greater or equal than the other
3 >= 3
# Test if one object is less than the other
3 < 4
# Test if one object is less or equal than the other
3 <= 4
```

### Logical operators

```
# Logical not with ~
~(2 == 2) # This returns false
# Elementwise and with a & b
(1 != 1) & (1 < 1) # This returns false
# Elementwise or with a | b
(1 >= 1) | (1 < 1) # This returns true
# Elementwise xor (exclusive or) with a ⊻ b; keyboard shortcut of \xor TAB
(1 != 1) ⊻ (1 < 1) # This returns false
```

### Other operators

```
# Determine if a value is in an array with x in arr
x = [11, 13, 19]
13 in x # This returns true
# Pipe values to a function with value |> fn
x |> (y -> length(y) + sum(y)) # This returns 43
```

## Vectors

Vectors are one-dimensional arrays in Julia. They allow a collection of items such as floats, integers, strings or a mix that allows duplicate values.

### Creating vectors

```
# Creating vectors with square brackets, [x1, x2, x3]
x = [1, 2, 3]
# Creating vectors with specific element types using Vector{type}([x1, x2, x3])
Vector{Float64}([1, 2, 3])
# Creating a sequence of numbers from a to b with a:b
37:100
# Creating a sequence of numbers from a to b in steps with a:step:b
1:2:101
# Create a vector that repeats m times where each element repeats n times
repeat(vector, inner=n, outer=m)
```

### Vector functions

```
# Sorting vectors with sort(x)
x = [9, 1, 4]
sort(x)
# Reversing vectors with reverse(x)
reverse(x)
# Reversing in-place with reverse!(x)
reverse!(x)
# Get unique elements of a vector with unique()
unique(x)
```

### Selecting vector elements

```
# Selecting the 6th element of a vector with x[6]
x = [9, 1, 4, 6, 7, 11, 5]
x[6]
# Selecting the first element of a vector with x[begin]
x[begin] # This is the same as x[1]
# Selecting the last element of a vector with x[end]
x[end] # This is the same as x[7]
# Slicing elements two to six from a vector with x[2:6]
x[2:6]
# Selecting the 2nd and 6th element of a vector with x[[2, 6]]
x[[2,6]]
# Selecting elements equal to 5 with x[x .== 5]
x[x .== 5]
# Selecting elements less than 5 with x[x .< 5]
x[x .< 5]
# Selecting elements in the vector 2, 5, 8 with x[in([2, 5, 8]).(x)]
x[in([2, 5, 8]).(x)]
```

## Math functions

```
# Example vector
x = [9, 1, 4, 6, 7, 11, 5]
# Get the logarithm of a number with log()
log(2)
# Get the element-wise logarithm of a vector with log.()
log.(x)
# Get the exponential of a number with exp()
exp(2)
# Get the element-wise exponential of a vector with exp.()
exp.(x)
# Get the maximum of a vector with maximum()
maximum(x)
# Get the minimum of a vector with minimum()
minimum(x)
# Get the sum of a vector with sum()
sum(x)
```

Note: The following code requires installing and loading the Statistics and StatsBase packages. This can be done with the command below.

```
]# Enter package mode
add Statistics # Add the Statistics package
add StatsBase # Add the StatsBase package
using Statistics # Load the package with using
using StatsBase # Load the package with using
# Get the mean of a vector with mean()
mean(x)
# Get the median of a vector with median()
median(x)
# Get quantiles of a vector with quantile(x, p)
quantiles(x, 4)
# Round values of a vector with round.(x, digits = n)
round.(x, 2)
# Round values of a vector with round.(x, digits = n)
round.(x, 4)
# Get the ranking of vector elements with StatsBase; ordinalrank()
ordinalrank(x)
# Get the variance of a vector with var()
var(x)
# Get the standard deviation of a vector with std()
std(x)
# Get the correlation between two vectors with cor(x, y)
y = [1, 4, 2, 10, 23, 16, 5]
cor(x, y)
```

## Getting started with characters and strings

Characters and strings are text data types in Julia. Characters refer to text data with exactly one character, and is referenced with single quotes `’ ‘`. Strings are sequences of characters, and are referenced with double or triple-double quotes `” “`.

```
# Creating a character variable with single quotes
char = ‘a’
# Creating a string variable with double quotes
string = “Hello World!”
# Creating a string variable with triple double quotes
string = “””Hello
World!”””
# Extract a single character from a string
string = “Hello World!”
string[1] # This extracts the first character
string[begin] # This extracts the first character
string[end] # This extracts the last character
# Extract a string from a string
string[1:3] # Extract first three characters as a string
string[begin:4] # Extract first four characters as a string
string[end-2: end] # Extract last three characters as a string
```

### Combining and splitting strings

```
# Combine strings using string()
string(“Hello ”, “World!”) # This returns Hello World!
# Interpolating strings with “$value” syntax
greet = “Hello”; whom = “World!”
“$greet, $whom” # Returns Hello, World!”
# Repeating strings with ^
"Hello! " ^ 3 # Returns Hello! Hello! Hello!
# Splitting strings on a delimiter with split()
split(“Hello, World!”, “,”)
```

### Finding and mutating strings

```
# Detecting the presence of a pattern in a string with occursin()
occursin(“Julia”, “Julia for data science is cool”) # This returns true
# Find the position of the first match in a string with findfirst()
findfirst(“Julia”, “Julia for data science is cool”) # This returns 1:5
# Convert a string to upper case with uppercase()
uppercase(“Julia”) # Returns JULIA
# Convert a string to lower case with lowercase()
uppercase(“JULIA”) # Returns julia
# Convert a string to title case case with titlecase()
titlecase(“JULIA programming”) # Returns Julia Programming
# Replace matches of a pattern with a new string with replace()
replace(“Learn Python on DataCamp.”, "Python" => "Julia") # Replaces Python with Julia
```

## Getting started with DataFrames

```
# Install the DataFrames and CSV packages
]
add DataFrames
add CSV
using DataFrames
using CSV
# Create a DataFrame with DataFrame()
df = DataFrame(numeric_column=1:4, # Fill whole column with a vector of integers
string_column= [‘M’, ‘F’, ‘F’, ‘M’], # Fill whole column with a vector of characters
from_number = 0, # Fill whole column with one number
from_string = "data frames” # Fill whole column with one string
)
# Select a row from a data frame with [ and column number
df[3, :] # Return the third row and all columns
# Select a column from a DataFrame using . and column name
df.string_column
# Select a column from a DataFrame using [ and column number
df[:, 2] # Return the second column and all rows
# Select an element from a data frame using [ and row and column numbers
df[1, 2] # Return the first row of the second column
```

### Manipulating data frames

```
# Concatenate two DataFraes horizontally with hcat()
df1= DataFrame(column_A= 1:3, column_B = 1:3)
df2 = DataFrame(column_C = 4:6, column_D = 4:6)
df3 = hcat(df1, df2) # Returns a four-column DataFrame with columns A, B, C, D
# Filter for rows of a data frame with filter() — Isolating all rows of df3 where column_A > 2
df_filter = filter(row -> row.column_A > 2, df3)
# Select columns of a data frame with select()
select(df3, 2) # Return the second column
# Select all columns of a data frame except those specified with select(Not())
select(df3, Not(2)) # Return everything except the second column
# Rename columns of a data frame with rename(old => new)
rename(df3, ["column_A" => "first_column"])
# Get rows of a data frame with distinct values in a column with unique(df, :col)
unique(df3, :column_A)
# Order the rows of a data frame with sort()
sort(df3, :numeric_column)
# Get DataFrame summary statistics with describe()
describe(df3)
```

Have this cheat sheet at your fingertips

Download PDFblog

### Progressing from MATLAB to Julia

cheat sheet

### Markdown Cheat Sheet

cheat sheet

### Excel Formulas Cheat Sheet

cheat sheet

### Python For Data Science Cheat Sheet For Beginners

tutorial

### Julia Programming Tutorial For Beginners

Bekhruz Tuychiev

20 min

code-along

### Julia for Absolute Beginners

John Verzani