Conditional Statements if/else

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Macro simple idea of textual substitution useful when you need a group of instructions or directives frequently.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
Lecture 7 Sept 29 Goals: Chapters 5 and 6. Scripts Sequence of instructions that we may want to run can be stored in a file (known as script). by typing.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Chapter 2: Algorithm Discovery and Design
Statistical Software An introduction to Statistics Using R Instructed by Jinzhu Jia.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Perl and Regular Expressions Regular Expressions are available as part of the programming languages Java, JScript, Visual Basic and VBScript, JavaScript,
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Introduction to Programming in R Department of Statistical Sciences and Operations Research Computation Seminar Series Speaker: Edward Boone
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Invitation to Computer Science 5 th Edition Chapter 2 The Algorithmic Foundations of Computer Science.
Lecture 15: Course Review BJ Furman ME 30 16MAY2011.
Language Find the latest version of this document at
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
4 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Control Structures Hara URL:
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Computational Methods in Astrophysics Dr Rob Thacker (AT319E)
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Computer Programming -1-
CS314 – Section 5 Recitation 9
Chapter 11 - JavaScript: Arrays
Introduction to Programming
Computer Programming Fundamentals
L – Modeling and Simulating Social Systems with MATLAB
Organization of Programming Languages
Expressions and Control Flow in JavaScript
MATLAB: Structures and File I/O
What is Bash Shell Scripting?
Arithmetic operations, decisions and looping
CS1100 Computational Engineering
Introduction to Python
PHP.
C Programming Getting started Variables Basic C operators Conditionals
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Programming Languages
Introduction to Computer Science
COMPUTER PROGRAMMING SKILLS
Matlab Basics.
Chapter 5 R programming Instructor: Li, Han.
Introduction to Programming
Review for Midterm 3.
Standard Version of Starting Out with C++, 4th Edition
REPETITION Why Repetition?
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

Conditional Statements if/else R> x <- 12 R> if(x>10) { + cat("x is >10") + } else { + cat("x is <=10") +} x is >10 R> x <- c(12, 16, 3) R> if(all(x>10)) cat("All values in x are >10") R> if(any(x>10)) cat("There is at least one value >10") There is at least one value >10

Loops FOR R> x <- 0 R> for(i in 1:5) { + x <- x+i +} R> x [1] 15 R> sum(1:5) [1] 15 R> l <- list(a=2, b=1:2, c=4) R> x <- 0 R> for(i in l) { x <- x+i } R> x [1] 7 8

break and next work as expected. Loops While R> x <- 0 R> i <- 1 R> while(i <=5) { x <- x+i; i<-i+1 } R> x [1] 15 break and next work as expected. Note: Loops are not very frequently used in R since most problems can be solved more efficiently using functions and vectorization.

Functions R is a functional programming language. Functions are objects of mode“function”. R> inc <- function(x) { x+1 } R> inc function(x) { x+1 } R> mode(inc) [1] "function" R> inc(5) [1] 6 R> inc(1:10) [1] 2 3 4 5 6 7 8 9 10 11 Since functions are regular (first class) objects they can be passed on as arguments and returned by functions.

Functions An R function is composed by: 􏰂 A name that will be used to call the function in the code chunk below, we call our function myFun. 􏰂A set on input formal arguments, that are defined in the parenthesis of the function constructor. The myFun example has two arguments, called i and j. It is possible to provide default values to arguments. 􏰂 A function body, with curly brackets (only the body is composed or a single expression). 􏰂 A return statement, that represents the output of the function. If no explicit return statement is provided, the last statement of the function is return by default. Functions only support single value. To return multiple values one needs to return a list of the respective return variables like return(list(i, j)). R> myFun <- function(i, j = 1) { + mn <- min(i, j) + mx <- max(i, j) + k <- rnorm(ceiling(i * j)) + return(k[k > mn/mx]) } R> myFun(1.75, 4.45) [1] 1.5953 0.4874 0.7383 R> myFun(1.75) ## j = 1 by default [1] 0.5758

Named arguments and defaults Functions Named arguments and defaults R> inc <- function(x, by = 1) { x + by } R> inc(5) [1] 6 R> inc(1:5, 10) [1] 11 12 13 14 15 R> inc(1:5, by=10) R> inc(by=10, x=1:5) R> inc(matrix(1:4, nrow=2), 10) [,1] [,2] [1,] 11 13 [2,] 12 14

Functions functions act on copies of their arguments, leaving the original variables intact. R> x <- 1 R> f1 <- function(x) { + x <- x + 10 +x +} R> R> f1(x) [1] 11 R> x ## unchanged [1] 1

Functions Functions have access to the variables defined outside of their body (global variables), while still keeping then unmodified. R> f2 <- function() { + x <- x + 10 +x +} R> R> f2() [1] 11 R> x ## still unchanged [1] 1

Functions can also be written that generate new functions . R> make.power <- function(n) + function(x) x^n +} R> square <- make.power(2) R> cube <- make.power(3) R> square function(x) x^n <environment: 0x2516358> R> get("n", environment(square)) [1] 2 R> square(2) [1] 4 R> get("n", environment(cube)) [1] 3 R> cube(2) [1] 8

Functions The ... arguments R> plt <- function(n, ...) { When an arbitrary number of arguments is to be passed to a function, one can use the ... special arguments. R> plt <- function(n, ...) { + plot(1:n, ...) } R> par(mfrow = c(1, 2)) R> plt(5, pch = 19, type = "b") R> plt(10, col = rbramp(10), pch = 15)

apply R> l <- list(1:3, 6, 7:3) lapply/sapply – apply functions to each element in a lists R> l <- list(1:3, 6, 7:3) R> lapply(l, FUN=function(x) { rev(x) }) [[1]] [1] 3 2 1 [[2]] [1] 6 [[3]] [1] 3 4 5 6 7 R> sapply(l, length) [1] 3 1 5

apply – apply functions to a matrix R> m <- matrix(1:9, nrow=3) R> apply(m, MARGIN=1, sum) [1] 12 15 18 R> apply(m, MARGIN=2, sum) [1] 61524 R> rowSums(m) [1] 12 15 18 R> colSums(m)

apply – apply functions to a matrix R> m <- matrix(1:9, nrow=3) R> apply(m, MARGIN=1, sum) [1] 12 15 18 R> apply(m, MARGIN=2, sum) [1] 61524 R> rowSums(m) [1] 12 15 18 R> colSums(m)

Measuring execution time We will be using the system.time function to compare for loops with and without initialisation and the apply functions while iterating over the elements of a list of length N = 10^4. We will then compute the mean of each element of the list and multiply it by its length as implemented in function f. R> N <- 10^4 R> ll <- lapply (sample(N), rnorm) R> f <- function(x) {mean(x) * length(x)} R> res1 <- c() R> system.time({ for (i in 1:length(ll)) res1[i] <- f(ll[[i]]) }) R> res2 <- numeric(length(ll)) R> system.time({ for (i in 1:length(ll)) res2[i] <- f(ll[[i]]) }) R> system.time({ res3 <-sapply(ll,f))}

Exercises Create a vector x by x <- runif(100). Write a function with the name avg_gt with two formal arguments: a vector x and a value gt. The functions computes the average of the values greater than gt in x. Write a version with a loop and if and one version without loops and if statements. Write a function small_matrix which computes the smallest value in each column of a given matrix. Create a random 5 × 5 matrix to test the function.

Exercises Load the obj test_text.Rdata How many characters and elements test has? Create an obj test2 using test and replacing “/” characters with “o” in all test elements. Create an obj test2 using test and replacing “<” characters with “” in all test elements. Replace the 1°, 2° and 3° character in each element of test2 with “AAA”

Finding Regex Matches in String Vectors The grep function takes your regex as the first argument, and the input vector as the second argument. If you pass value=FALSE or omit the value parameter then grep returns a new vector with the indexes of the elements in the input vector that could be (partially) matched by the regular expression. If you pass value=TRUE, then grep returns a vector with copies of the actual elements in the input vector that could be (partially) matched. > grep("a+", c("abc", "def", "cba a", "aa"), perl=TRUE, value=FALSE) [1]1 3 4 > grep("a+", c("abc", "def", "cba a", "aa"), perl=TRUE, value=TRUE) [1] "abc" "cba a" "aa" The grepl function takes the same arguments as the grep function, except for the value argument, which is not supported. grepl returns a logical vector with the same length as the input vector. > grepl("a+", c("abc", "def", "cba a", "aa"), perl=TRUE) [1] TRUE FALSE TRUE TRUE

Exercises Load the obj test_text.Rdata How many elements contain the at least two “l”? How many elements contain 4 to 6 numbers? How many elements contain space characters ? How many elements start and end with at least 4 word character?

Exercises Search from NCBI GE dataset cel[Supplementary Files] and download the text file Using the function scan load the file as test_NCBI OBJ. How many elements contain “ftp” and “GSE”? (use length) How many elements contain the world “Affy”? Select each element before the world “Affy”