R:If, else and loops

Similar documents
Math 96--Radicals #1-- Simplify; Combine--page 1

Lecture 3: Basics of R Programming

Lecture 3: Basics of R Programming

1 Matrices and Vectors and Lists

Polynomial Functions I

Data Structures STAT 133. Gaston Sanchez. Department of Statistics, UC Berkeley

BRAND STANDARD GUIDELINES 2014

BRAND BOOK. Copyright 2016 WashU Student Union Student Union Brand Guidebook 1

Intermediate Programming in R Session 4: Avoiding Loops. Olivia Lau, PhD

Introduction to R. Nishant Gopalakrishnan, Martin Morgan January, Fred Hutchinson Cancer Research Center

Wisconsin Retirement Testing Preparation

CS246: Mining Massive Datasets Jure Leskovec, Stanford University

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

ITS Introduction to R course

Industrial Control. 50 to 5,000 VA. Applications. Specifications. Standards. Options and Accessories. Features, Functions, Benefits.

Introduction to Matlab. CSE555 Introduction to Pattern Recognition Spring 2011 recitation

Lab #10 Multi-dimensional Arrays

Industrial Control. 50 to 5,000 VA. Applications. Specifications. Standards. Options and Accessories. Features, Functions, Benefits.

Ascenium: A Continuously Reconfigurable Architecture. Robert Mykland Founder/CTO August, 2005

Teacher Assignment and Transfer Program (TATP) On-Line Application Quick Sheets

II.Matrix. Creates matrix, takes a vector argument and turns it into a matrix matrix(data, nrow, ncol, byrow = F)

CMSC 330, Fall 2013, Practice Problems 3

Lesson 12: Angles Associated with Parallel Lines

Stacks & Queues. Kuan-Yu Chen ( 陳冠宇 ) TR-212, NTUST

Sequence alignment is an essential concept for bioinformatics, as most of our data analysis and interpretation techniques make use of it.

HEL HEL HEL HEL VETIC HEL VETIC HEL HEL VETICA HEL HEL ETICA ETIC VETIC HEL VETIC HEL HEL C VETICA ETI- HEL HEL VETI HEL VETICA VETIC HEL HEL VETICA

Intro to R. Some history. Some history

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Visual Identity Guidelines. Abbreviated for Constituent Leagues

Tranont Mission Statement. Tranont Vision Statement. Change the world s economy, one household at a time.

Control Flow Structures

recruitment Logo Typography Colourways Mechanism Usage Pip Recruitment Brand Toolkit

Lecture-14 Lookup Functions

November 25, Mr. Paul Kaspar, PE City Engineer City of Bryan Post Office Box 1000 Bryan, Texas 77802

Decision Making in C

the R environment The R language is an integrated suite of software facilities for:

"Charting the Course... CA-View Administration. Course Summary

JME Language Reference Manual

7 Control Structures, Logical Statements

Teacher Assignment and Transfer Program (TATP) On-line Teacher Application Quick Sheets

The ABC s of Web Site Evaluation

Unifi 45 Projector Retrofit Kit for SMART Board 580 and 560 Interactive Whiteboards

Armstrong State University Engineering Studies MATLAB Marina 2D Arrays and Matrices Primer

Practice for Learning R and Learning Latex

Program Development (SAS IML)

T10/05-233r2 SAT - ATA Errors to SCSI Errors - Translation Map

HIM a. LCD error is present and there IS an ABN for the services: a. HIM will add the GA modifier b. Select Refresh Claim

1.2 Round-off Errors and Computer Arithmetic

Computer Programming: C++

Algorithms and Data Structures

Queues. Kuan-Yu Chen ( 陳冠宇 ) TR-212, NTUST

Sparse matrices, graphs, and tree elimination

MINIATURE Z-AXIS HALL EFFECT JOYSTICK

Brand Standards. V1 For Internal Use. Newcastle Systems Brand Standards 1

Data Frames and Control September 2014

How to Register for Summer Camp. A Tutorial

Brand Guidelines October, 2014

Package bigalgebra. R topics documented: February 19, 2015

Questions Bank. 14) State any four advantages of using flow-chart

PracticeAdmin Identity Guide. Last Updated 4/27/2015 Created by Vanessa Street

CMSC 2833 Lecture Memory Organization and Addressing

14K Mixable Rings 1/ 2 ctw, $1499. Silver Diamond Pendant 1/6 ctw, $299

Introduction to R. Adrienn Szabó. DMS Group, MTA SZTAKI. Aug 30, /62

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

Introduction to R, Github and Gitlab

CMAT Language - Language Reference Manual COMS 4115

Similar Polygons Date: Per:

Computational Finance

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Ecffient calculations

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

BRANDING AND STYLE GUIDELINES

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Decision Making and Loops

Quick R Tutorial for Beginners

Ch.5. Loops. (a.k.a. repetition or iteration)

Media Kit & Brand Guidelines

Colorado State University Department of Mechanical Engineering. MECH Laboratory Exercise #1 Introduction to MATLAB

SUM, AVERAGE, MEDIAN, MIN,

Data Classes. Introduction to R for Public Health Researchers

Statistical Programming with R

Package future.apply

WINSTON WORKSTATION INSTALLATION INSTRUCTIONS. STEP 1 COLUMN...Page 2

Section 8: Monomials and Radicals

Growing Our Own Through Collaboration

Extremely short introduction to R Jean-Yves Sgro Feb 20, 2018

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Following is the general form of a typical decision making structure found in most of the programming languages:

Homework Set 5 (Sections )

Basic matrix math in R

"Charting the Course... MOC A Planning, Deploying and Managing Microsoft Forefront TMG Course Summary

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Introduction to Programming Using Java (98-388)

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Programming with R. Educational Materials 2006 S. Falcon, R. Ihaka, and R. Gentleman

TABLE OF CONTENTS. 3 Intro. 4 Foursquare Logo. 6 Foursquare Icon. 9 Colors. 10 Copy & Tone Of Voice. 11 Typography. 13 Crown Usage.

Transcription:

R:If, else and loops Presenter: Georgiana Onicescu January 19, 2012 Presenter: Georgiana Onicescu R:ifelse,where,looping 1/ 17

Contents Vectors Matrices If else statements For loops Leaving the loop: stop, break, next commands Other loops:while and repeat Avoiding the loops: apply function Presenter: Georgiana Onicescu R:ifelse,where,looping 2/ 17

Vectors A one column list of elements (a scalar is also a vector) - a one dimensional array. Methods of creating vectors: vec.a = c(2,3,4,5,6,7,8,9,10,11,12,13,14,15) vec.a = c(2:15) vec.a = as.numeric(c( -.01, 2.5, C )) vec.a = seq(2,15,by=1) vec.a = c(a, b, c, d) Presenter: Georgiana Onicescu R:ifelse,where,looping 3/ 17

Matrices A combination of vectors. Can combine by column or by row. Methods of creating matrices: vec1 = c(2,3,4,5,6,7,8,9,10,11,12,13,14,15) vec2 = c(as.numeric(22:35)) vec3 = seq(42,55,by=1) vecb = c( aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm, nn ) matr1 = cbind(vec1, vec2, vec3) matr2 = rbind(vec1, vec2, vec3) matr3 = cbind(vec1, vec2, vec3, vecb) matr4 = matrix(vecb,7,2) matr5=matrix(vec1,ncol=2,byrow=true) Presenter: Georgiana Onicescu R:ifelse,where,looping 4/ 17

If else statements if ( statement1 ) statement2 else statement3 If statements can be nested: if ( statement1 ) statement2 else if ( statement3 ) statement4 else if ( statement5 ) statement6 else statement8 Presenter: Georgiana Onicescu R:ifelse,where,looping 5/ 17

If else statements. Example Example: Calculating median of a single sample x=c(2,7,1,8,9) med=function(x) { odd=length(x)%% 2 if (odd==0) { med=(sort(x)[length(x)/2]+sort(x)[1+length(x)/2])/2 } else med=sort(x)[ceiling(length(x)/2)] } m=med(x) m 7 Note:ceiling takes a single numeric argument and returns the smallest integer not less than the corresponding elements of the argument. Presenter: Georgiana Onicescu R:ifelse,where,looping 6/ 17

Ifelse statements Syntax: ifelse(test, truevalue, falsevalue) ifelse operates on vectors therefore avoiding loops Example: y=log(c(3,0.5,2,4)) ifelse(y<0,na,y) Presenter: Georgiana Onicescu R:ifelse,where,looping 7/ 17

For loop for(i in 1:n){ execute commands } Example: Calculating factorials for an integer x: x!=x*(x-1)*(x-2)*(x-3)*...2*1 fac=function(x){ f=1 if (x<2) {f=1} else {for (i in 2:x) f=f*i } return (f) } Presenter: Georgiana Onicescu R:ifelse,where,looping 8/ 17

For loop The for loop can iterate any sequence.examples: for (i in 1:2) print(i) 1 2 for (i in (1:4)-2) print(i) -1 0 1 2 library(mass) data(phones) for(var in names(phones)) print(var) year calls for(func in c(sin,cos)) print(func(pi)) 1.224606e-16-1 Presenter: Georgiana Onicescu R:ifelse,where,looping 9/ 17

Leaving the loop:stop stop on condition and print error message: a = 1:10 b = NULL for (i in seq(along=a)) { if (a[i]<5 a[i]>8) { b = c(b,a[i]) } else { stop( values need to be <5 ) } } Error: values of a need to be <5 b 1 2 3 4 Presenter: Georgiana Onicescu R:ifelse,where,looping 10/ 17

Leaving the loop:break break:stop on condition without printing the error message rm(b) a = 1:10 b = NULL for (i in seq(along=a)) { if (a[i]<5 a[i]>8) { b = c(b,a[i]){ else {break( values of a need to be <5 )}} b 1 2 3 4 Presenter: Georgiana Onicescu R:ifelse,where,looping 11/ 17

Leaving the loop:next next rm(b) a = 1:10 b = NULL for (i in seq(along=a)) { if (a[i]<5 a[i]>8) { b = c(b,a[i]){ else {next}} b 1 2 3 4 9 10 Presenter: Georgiana Onicescu R:ifelse,where,looping 12/ 17

Other loops: While When using while, we need to set up an indicator variable and change its value within each iteration. Example:Calculation of the factorial x=4 f=1 t=x while (t > 1){ f=f*t t=t-1 } f 24 Presenter: Georgiana Onicescu R:ifelse,where,looping 13/ 17

Other loops:repeat Repeat:We must have a logical escape clause that leads to a break command x=4 f=1 t=x repeat { if (t < 2) break f=f*t t=t-1 } f 24 Presenter: Georgiana Onicescu R:ifelse,where,looping 14/ 17

Avoiding the loops:apply Syntax: apply(x, MARGIN, FUN, ARGs) X is an array, matrix or data.frame; MARGIN: 1 for rows, 2 for columns, c(1,2) for both; FUN: one or more functions; ARGs: possible arguments for function Examples: matrix = matrix(c(1:10, 11:20), nrow = 10, ncol = 2) apply(matrix, 1, mean) apply(matrix, 2, mean) apply(matrix, 1:2, function(x) x*2) Presenter: Georgiana Onicescu R:ifelse,where,looping 15/ 17

References Michael J. Crawley. The R book.wiley,2007 Johns Hopkins BST 140.776 Statistical Computing: http://www.biostat.jhsph.edu/ bcaffo/statcomp/files/ ingo.r.2.notes.pdf http://manuals.bioinformatics.ucr.edu/home/programmingin-r Presenter: Georgiana Onicescu R:ifelse,where,looping 16/ 17

QUESTIONS? Source:Paul Murell.R graphics, Second edition. Presenter: Georgiana Onicescu R:ifelse,where,looping 17/ 17