Chapter 5 R programming Instructor: Li, Han.

Slides:



Advertisements
Similar presentations
Statement-Level Control Structures
Advertisements

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.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Objectives Using functions to organize PHP code
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Statistical Software An introduction to Statistics Using R Instructed by Jinzhu Jia.
Invitation to Computer Science, Java Version, Second Edition.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Control Structures A control structure is simply a pattern for controlling the flow of a program module. The three fundamental control structures of a.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Branches and Program Design
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Chapter 5: Structured Programming
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
JavaScript, Fourth Edition
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
JavaScript, Sixth Edition
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
G. Pullaiah College of Engineering and Technology
Chapter 4: Control Structures I (Selection)
Chapter 5: Structured Programming
Chapter 7 User-Defined Methods.
Repetition Structures Chapter 9
Conditional Statements if/else
Selection—Making Decisions
Expressions and Control Flow in JavaScript
Chapter 8: Control Structures
Chapter 5: Control Structures II
Ch.5 Writing functions.
Chapter 4: Control Structures I (Selection)
Chapter 7 Conditional Statements
Statement-Level Control Structures
Conditional and iterative statements
Computer Science Core Concepts
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
C Programming Getting started Variables Basic C operators Conditionals
CHAPTER 5: Control Flow Tools (if statement)
CSE 231 Lab 2.
Lecture 4: Selection Control Structure
Presentation transcript:

Chapter 5 R programming Instructor: Li, Han

Contents control flow: for, while, if-else, switch user defined function break stop(), warning() and message() global vs local environment R vectorization

R has the standard control structures you'd expect to see in a modern programming language. statement is a single R statement or a compound statement separated by semicolons or newline. cond is an expression that is judged to be true or false. expr is a statement that evaluates a number or character string. seq is a sequence of numbers or character strings.

Repetition and looping Looping constructs repetitively execute a statement or series of statements until a condition is false. These include structures of for while

for (var in seq) statement The for loop executes a statement repetitively until the last element in the sequence seq. The syntax is for (var in seq) statement Example 1 (for loop) for (i in 1:10) { print("Hello") }

while (cond) statement A while loop executes a statement repetitively until the condition is no longer true. The syntax is while (cond) statement Example 2 (while loop) i <- 10 while (i > 0) { print("Hello") i <- i - 1 }

In the above example, if you add 1 on each loop, R would never stop saying “Hello”. This is why while loops can be more dangerous than other looping constructs. In such case, you need to "stop" the loop forcefully.

Looping in R can be inefficient and time consuming when you are processing the rows or columns of large datasets. Whenever possible, it's better to use R's built-in numerical and character functions in conjunction with the apply family of functions.

Example 3 (caculate the column means) x <- rnorm(100) y <- matrix(x, 10,10) z <- rep(0,ncol(y)) for (i in 1:ncol(y)) { z[i]=mean(y[,i]) } w <- apply(y, 2, mean)

Conditional execution In conditional execution, a statement or statements are only executed if a specified condition is met. These constructs include ifelse if-else switch

ifelse The ifelse construct is a compact and vectorized version of the if-else construct. The syntax is ifelse(cond, statement1, statement2) Example 4 (ifelse) score <- 80 ifelse(score > 60, print("Passed"), print("Failed")) outcome <- ifelse(score > 60, "Passed", "Failed")

if-else For the above example, we could also use the syntax if(cond){ statement1} else{statement2} Example 5 (if-else) score <- 80 if (score > 60) {print("Passed")} else {print("Failed")}

If we have more than one condition to evaluate, we could use multiple if-else. The syntax is if (cond 1) { statement 1 } else if (cond 2) { statement 2 } ... { } else if (cond k) { statement k } else { statement n }

Example 6 (multiple conditions) score <- 90 If (score >85) { print("Excellent") } else if (score >75) { print("Good") } else if (score >60) { print("Passed") } else{ print("Failed") }

switch switch chooses statements based on the value of an expression. The syntax is switch(expr, ...) Then it compares the expr with the predefined string that matches it, and then excutes the corresponding statements.

Example 7 (switch) feelings <- c("sad", "afraid") for (i in feelings) { print( switch(i, happy = "I am glad you are happy", afraid = "There is nothing to fear", sad = "Cheer up", angry = "Calm down now" ) }

functions We could build our own functions in R. The structure of a function looks like this: myfunction <- function(arg1, arg2, ... ) { statements return(object) } Objects in the function are local to the function. The object returned can be any data type, from a single number to a list.

Example 8 (calculate the center and spread of the data) mystats <- function(x, parametric=TRUE, print=FALSE) { if (parametric) { center <- mean(x); spread <- sd(x) } else { center <- median(x); spread <- mad(x) } if (print & parametric) { cat("Mean=", center, "\n", "SD=", spread, "\n") } else if (print & !parametric) { cat("Median=", center, "\n", "MAD=", spread, "\n") result <- list(center=center, spread=spread) return(result)

set.seed(1234) x <- rnorm(500) y <- mystats(x) y <- mystats(x, parametric=FALSE, print=TRUE)

break In a loop, if we want to stop it, use break. Example 9 (break) for(i in 1:10){ print(i) if(i>3){break} }

stop() If you want to stop the current excution, use stop(). Example 10 (stop) for(i in 1:10){ print(i) if(i>3){stop("It is larger than 3.")} print("fine") }

warning() Example 11(warning) for(i in 1:10){ print(i) if(i>3){warning("It is larger than 3.")} print("fine") }

message() Example 12 (message) for(i in 1:10){ print(i) if(i>3){message("It is larger than 3.")} print("fine") }

global vs local environment In R, each function defines an environment that includes all its local variables that can not be accessed from outside. If the function finishes running, all the local variables disappear. A local function can access the variables in its parent environment when running. Note that it actually copies the global variable, and it is not the global variable itself. So it can not change the value of the global variable.

Example 13 (global vs local environment) w <- 12 f <- function(){ y <-5 h <- function(z){return(z^2)} w <- 10 print(w) return(h(y)) } f() w y

R vectorization Compare with the following two examples that summarize the sum of those x>0. Example 14 (use R vectorization if possible) x <- runif(1000000) y =z=0 system.time( for(i in 1:length(x)){ if(x[i]>0){y=y+x[i]} } ) system.time(sum(x[x>0]))

Summary In this session, we have learned how to use the control flow structures and build functions in R.