Lecture 2 - Algorithms to Functions Flashcards
What kind of statement is used for a single condition?
If statement
What statement is used for multiple conditions?
If else statement
What statements are used in nested conditions?
Multiple if else statements
What function is used in Multibranch condition?
Switch( )
What kind of loop is used when iterations are known from outset?
For loop
What kind of loop is used when iterations are unknown at outset?
While loop, repeat loop
What is vectorisation?
Implicit Iteration
e.g.
bob
What is the apply function for?
The apply function can be used to apply the same function for example to some large dataset by iterating down a certain column to calculate the same summary statistic
Vectorised Conditional Statement
Acts upon a vector like data structure conditional tests upon each element
What is a function?
Compartmentalised and reusable blocks of code
What is an argument?
Information entering a function.
Good practice to have names.
Can be defined in any order
How do you set a default for an argument?
Assign a value to the argument when the function is defined.
What is the principle of least privilege?
By encapsulating in a function user does not make changes to objects outwith the function.
What is the DRY principle?
Don’t repeat yourself
What are the two different methods to make arguments available to functions?
- Pass by value
- Pass by reference
What is pass by value?
A copy is made of each object being sent into the function.
Memory address of object in the function environment differs from object address in calling environment.
Changes made to the object while inside the function does not change the objects value in the calling environment.
What is pass by reference?
The address of the object is sent into the function.
Any changes made to the object in the function is reflected in the calling environment
Pros and cons of pass by value
Pro:
Safer - changes made inside the function are not reflected outside the function.
Con:
Inefficient - copy of information needs to be made to store information in two memory locations.
Pros and cons of pass by reference
Pro -
More efficient - doesn’t need to make copy of info to store in different locations
Con -
More dangerous
Pure functions
Do not have side effects.
Always map same input into to same output and otherwise leave calling environment unaltered.
3 examples of impure functions
library( ) - if a function loads a package, it remains loaded.
setwd( ) - persistent effect after function finishes
par( ) - graphical parameter changes persist.
How to make impure functions pure?
using the function on.exit( ) will restore previous state when function finishes
Are the arguments for standard functions in R pass by value or pass by reference?
Pass by value