Lecture 3 Loops and conditions Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

While Loops and If-Else Structures
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Introduction to Computing Science and Programming I
Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
CHAPTER 5: LOOP STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Pseudocode and Algorithms
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
PowerPoint Hints & Tips This example file gives you some examples of good and bad practice plus problem-solving tips.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
PowerPoint Hints & Tips This example file gives you some examples of good and bad practice plus problem-solving tips.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Conditional Execution
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
© Jalal Kawash Programming Peeking into Computer Science 1.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Structured Programming: Debugging and Practice by the end of this class you should be able to: debug a program using echo printing debug a program using.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
ASP-5-1 ASP Control Structures Colorado Technical University IT420 Tim Peterson.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
JavaScript, Fourth Edition
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
While and If-Else Loops ROBOTC Software. While Loops While loop is a structure within ROBOTC Allows a section of code to be repeated as long as a certain.
Working with Loops, Conditional Statements, and Arrays.
The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development Lecture 2 Debugging,
Algorithms and Pseudocode
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Finding zeros (also called roots) of a function Overview: Define the problem Methods of solution Graphical Newton’s Bisection Secant.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Lecture 4 Speeding up your code Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.
Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition.
Lecture 9 Debugging R code Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.
Lecture 5 More loops Introduction to maximum likelihood estimation Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University.
Computational Methods in Astrophysics Dr Rob Thacker (AT319E)
Lecture 2 Functions Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
Lecture 8 Speeding up your code
Scripts & Functions Scripts and functions are contained in .m-files
Agenda Control Flow Statements Purpose test statement
Control Structures: Part 1
Conditional Statements
More Selections BIS1523 – Lecture 9.
While Loops and If-Else Structures
Coding Concepts (Basics)
Logical Operations In Matlab.
While Loops and If-Else Structures
While Loops and If-Else Structures
While Loops and If-Else Structures
While Loops and If-Else Structures
While Loops and If-Else Structures
Week 7: Computer Tools for Problem Solving and Critical Thinking
While Loops And If-Else Structures
Presentation transcript:

Lecture 3 Loops and conditions Trevor A. Branch FISH 553 Advanced R School of Aquatic and Fishery Sciences University of Washington

Programming Consider the following problem – We have data on age and length for some animals ("lect3.csv") – The number of data points for each animal is not the same – We want to regress length on age for each animal – We want to plot the slopes using a histogram You could do this line by line in a script... painful! Instead devise a part-by-part strategy – Read in the data – For each animal using a loop Check if there are two or more data points If yes, regress length on age for that animal Store the slope – Plot a histogram of the slopes of each regression

Looping Although vector operations can do many things, and are quick, often we need to repeat things Loops in R are of this form for (i in set) { #do something } This is a very flexible structure, try the following: for (i in seq(from=1,to=5,by=1)) { print(i) } for (i in 1:100) { print(i) } for (i in c("1","N","L")) { print(i) } i is a counter, conventionally we use i, j, k for counters By far the most common useage

Looping: what is happening? line 1 for (i in c(1,4,5,8)) { line 2 print(i) line 3 } line 4 print(i) Step Line Value of i Output

Looping through species Imagine we need to calculate the mean petal and sepal lengths for every species in the iris data set loop.iris <- function (data=iris) { for (i in unique(data$Species)) { meanSepalLength <- mean(data[data$Species==i,]$Sepal.Length) meanPetalLength <- mean(data[data$Species==i,]$Petal.Length) cat(i, meanSepalLength, meanPetalLength, "\n") } loop.iris() Pro tip: everything inside the function is indented three spaces, inside the loop by six spaces, allowing reader to easily see which statements are contained within each section of code

Most common way I use loops species <- sort(unique(iris$Species)) nspecies <- length(species) mean.lengths <- vector(length=nspecies) for (i in 1:nspecies) { species.data <- iris[iris$Species==species[i],] plot(hist(species.data$Sepal.Length)) mean.lengths[i] <- mean(species.data$Sepal.Length) print(mean.lengths[i]) cat("Running species ", i,"\n") } Species names How many species Store answers here Extract all data for this particular species Mean sepal length for this species Plot the data

In-class exercise 1 Modify the sin.period() function on the next slide, to have a parameter p that is a vector of periods, and then the function plots for each element of p the function sin(x/p) where p is the period and x ranges from 0 to 2  Use the call par(mfrow=c(3,3)) to create 9 subplots and run your function for p <- c(0.05, 0.1, 0.25, 0.5, 1, 1.5, 2, 2.5, 5) If you finish early, try to make the function as general as possible

sin.period <- function(period) { xvals <- seq(from=0, to=2*pi, length=100) yvals <- sin(xvals/period) plot(x=xvals, y=yvals, type="l", lty=1, xaxs="i", lwd=2) } sin.period(period=1) name of function arguments of function R commands which can include calls to other functions start of the function end of the function calling the function passing values to the function arguments Function to modify

The while-loop The while-loop is rarely used because the for-loop can almost always be used for looping But occasionally we don’t know how many times to execute the loop In such cases we use a while loop, which executes a series of statements for as long as some condition remains true The general syntax is while (condition) { #statements }

While-loop example If there are 10,000 polar bears in year 2015 and they are declining at 9% per year, in what year will they fall below 500 individuals? polar.loop <- function(N, year=2015) { while (N>500) { N <- N*0.91 year <- year+1 } return(year) } > polar.loop(N=10000) [1] 2047 Pro-tip: when you end up in an infinite loop with no stopping point, press to stop it running!

If statements Often we need to check that our data are correct before proceeding with an analysis, for example we could not plot x and y if their lengths were different plotxy <- function(x, y) { if (length(x) == length(y)) { plot(x,y) } else { print("Lengths of x and y are different") } > plotxy(x=1:5, y=5:1) > plotxy(x=1:5, y=4:1) [1] "Lengths of x and y are different"

Generic if statement The generic if-statement is: if (condition) { #statements } Common conditions in if-statements if (x==5) if (x==5 & y==7) if (x>=5) if (x==5 | y>=17) if (x %in% c(1,2,3,5)) if (!found) if (!is.na(x) & y==3)

Conditions Conditions in an if-statement are based on Boolean operators == Boolean equals (don’t use =) != not equals >=,, < greater and less than | or (comparing single element) & and (comparing single element)

Complicated if-then-else statements sum.bigger <- function(x, y) { if(length(x) != length(y)) { print("not equal lengths") } else { if (sum(x) > sum(y)) { print("x bigger") } else { print("x smaller or equal") } > sum.bigger(x=1:5, y=6:10) [1] "x smaller or equal" Calling an if-then-else statement within an if- then-else statement. Line indentation is critical!

Switch statement Sometimes you might find yourself writing multiple nested if statement For example, if x==1 then do something, else if x==2 then do something else, else if x==3 then do a third thing, else if x==4 then do a fourth thing... Instead, use a switch statement This evaluates the first parameter, and does different things depending on its value Switch statements are rarely used but very useful when needed

Switch statement: text values require(stats) centre <- function(x, type) { return(switch(type, mean = mean(x), median = median(x), trimmed = mean(x, trim =.1), "No function matches") ) } > x <- rcauchy(10) > centre(x, "mean") [1] > centre(x, "median") [1] > centre(x, "unknown") [1] "No elements match" This is like writing: if (type=="mean") { temp <- mean(x) } else { if (type=="median") { temp <- median(x) } else { if (type=="trimmed") {... return(temp)

Switch statement: number values alternatives <- function(x, value) { return(switch(value, "You chose option 1", x^3, "Option 3") ) } > alternatives(x=3,value=1) [1] "You chose option 1" > alternatives(x=3,value=2) [1] 27 > alternatives(x=3,value=3) [1] "Option 3" For numbers, it returns the argument of switch after the value

Tips in RStudio for coding Code->Reindent Lines (ctrl+I) automatically indents your code correctly Code->Comment/Uncomment Lines (ctrl+shift+C) adds # before every line that is highlighted, to comment out the code so that it will not run If you have just run a section of code, and then changed part of it, clicking the button below (or ctrl+shift+P) will rerun that code with no need to re- select it

In-class exercise 2 Now try to solve the problem mentioned at the start of the lecture (next slide) Hints – Before coding, outline the problem conceptually. How would you do it by hand? – I used a for -loop and an if -statement – To extract the slope from a regression reg <- lm(y~x) slope <- coefficients(reg)[2] – Use the hist() function for the histogram – You don’t know how many animals there are or whether there are enough data points to do a regression. How will you handle that?

In-class exercise 2 (continued) Consider the following problem – We have data on age and length for some animals ("lect3.csv") – The number of data points for each animal is not the same – Regress length as a function of age for each animal – Plot the slopes using a histogram Devise a step-by-step strategy – Read in the data – For each animal Check if there are two or more data points If yes, regress length on age for that animal Store the slope – Plot a histogram of the slopes of each regression