Iteration and functions: if()
Day 5a - Introduction to R for Life Sciences
if() (and else)
if( some.condition ) {
# do stuff
}
some.condition is simply a single-valued logical.
As with functions, and for-loops: indent, and use curly braces
if ( some.condition) {
# do stuff
} else {
# do other stuff
}
if
Conditions often look like if( a > b ) { … }
But you can also use logicals: if ( print.to.file ) { … }
Never write: if (print.to.file == TRUE) { … }
Nor: if ( adjust.pvalues == FALSE ) { … }.
Instead, write
if (! adjust.pvalues) { … }
Condition must be a single value
if (big.vector) { do.stuff() }
Warning message:
In if (big.vector) { do.stuff() } :
the condition has length > 1 and only the first element will be used
Use aggregate functions such as any() or all()
Inside if(), prefer && and || for logical AND and logical OR
(as opposed to & and | )
if() statement inside for-loop
Avoid using the for-loop
variable in an if-condition
for(g in genes) {
if ( data[g, 'strand'] == '-') {
data[g, 'len' ] <- -data[g, 'len']
}
}
It’s often a sign that things can
be simplified using vector
notation:
rev <- data[genes, 'strand'] == '-'
data[rev , 'len' ] <- -data[rev, 'len' ]
The End
&& and ||
They work on only the first
element
(and silently ignore the rest)
They short-circuit: only as many
as needed are evaluated:
if( is.null(s) || s=="" ) { # double bar
stop("string missing")
}
There may be no first element:
> s<-NULL
> s==""
logical(0)
> if( is.null(s) | s=="" ) { # single bar
stop("string missing")
}
Error in if (is.null(s) | s == "") { :
argument is of length zero
The triple-dot
The triple dot (…) collects ‘the rest’ of the arguments
Inside the function, this ‘rest’ can be passed on to other calls
(provided those functions take triple-dot arguments)
Warns about arguments that never get used
This magically endows your function with extra arguments
Often used for plotting functions: main, sub, xlab,ylab, xlim, ylim, ...
Example
my.plot <- function(x, ...) {
plot(density(x), ...)
rug(x, ...)
}
my.plot(x, main="slx5", xlab="M",
col="red", xlim=c(-4,4),
lwd=2, ticksize= -0.02)
Warning messages:
1: In plot.window(...) : "ticksize" is not a graphical
parameter
2: In plot.xy(xy, type, ...) : "ticksize" is not a graphical
parameter
3: In axis(side = side, at = at, labels = labels, ...) :
"ticksize" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
"ticksize" is not a graphical parameter
5: In box(...) : "ticksize" is not a graphical parameter
6: In title(...) : "ticksize" is not a graphical parameter

More Related Content

PPT
Operation on string presentation
PPTX
Implementation Of String Functions In C
PDF
PDF
Scala: Pattern matching, Concepts and Implementations
PPTX
Managing I/O & String function in C
PPTX
Array and string
PPTX
Strings
PPT
Array
Operation on string presentation
Implementation Of String Functions In C
Scala: Pattern matching, Concepts and Implementations
Managing I/O & String function in C
Array and string
Strings
Array

What's hot (20)

PPT
DATASTRUCTURES UNIT-1
PPTX
One dimensional arrays
PPTX
C programming - String
PPTX
Array, string and pointer
PDF
Python data handling
PPT
Strings
PPTX
DOC
Lesson 4
PPTX
Computer programming 2 Lesson 10
PPT
Recursion - Algorithms and Data Structures
PDF
14 ruby strings
PPTX
C# Strings
PPTX
Strings in C
PPTX
13string in c#
DOC
String in c
PPTX
Data Structures - Lecture 3 [Arrays]
PDF
PDF
Character Array and String
DATASTRUCTURES UNIT-1
One dimensional arrays
C programming - String
Array, string and pointer
Python data handling
Strings
Lesson 4
Computer programming 2 Lesson 10
Recursion - Algorithms and Data Structures
14 ruby strings
C# Strings
Strings in C
13string in c#
String in c
Data Structures - Lecture 3 [Arrays]
Character Array and String
Ad

Similar to Day 5a iteration and functions if().pptx (20)

PDF
Functional programming ii
PDF
Scala Paradigms
PPT
Rewriting Java In Scala
ODP
Knolx Session : Built-In Control Structures in Scala
PDF
ApplicativeError functions handling and recovering from errors: A mnemonic to...
PPT
Scala - brief intro
PDF
Programming in Scala: Notes
PPSX
Scala @ TomTom
PDF
Python to scala
ODP
Introduction to Scala
PDF
Python idiomatico
PDF
Pydiomatic
PPTX
Scala for curious
PDF
Introduction to Scala for JCConf Taiwan
PDF
Scala taxonomy
PDF
iRODS Rule Language Cheat Sheet
PDF
3 kotlin vs. java- what kotlin has that java does not
PPTX
Python functions part12
PDF
Introducing Pattern Matching in Scala
PPTX
Scala training workshop 02
Functional programming ii
Scala Paradigms
Rewriting Java In Scala
Knolx Session : Built-In Control Structures in Scala
ApplicativeError functions handling and recovering from errors: A mnemonic to...
Scala - brief intro
Programming in Scala: Notes
Scala @ TomTom
Python to scala
Introduction to Scala
Python idiomatico
Pydiomatic
Scala for curious
Introduction to Scala for JCConf Taiwan
Scala taxonomy
iRODS Rule Language Cheat Sheet
3 kotlin vs. java- what kotlin has that java does not
Python functions part12
Introducing Pattern Matching in Scala
Scala training workshop 02
Ad

More from Adrien Melquiond (11)

PPTX
Day 1a welcome introduction
PDF
R course ggplot2
PDF
Day 5b statistical functions.pptx
PDF
Day 4b iteration and functions for-loops.pptx
PDF
Day 4a iteration and functions.pptx
PDF
Day 3 plotting.pptx
PDF
Day 2b i/o.pptx
PDF
Day 2 repeats.pptx
PDF
Day 1d R structures & objects: matrices and data frames.pptx
PDF
Day 1c access, select ordering copy.pptx
PDF
Day 1b R structures objects.pptx
Day 1a welcome introduction
R course ggplot2
Day 5b statistical functions.pptx
Day 4b iteration and functions for-loops.pptx
Day 4a iteration and functions.pptx
Day 3 plotting.pptx
Day 2b i/o.pptx
Day 2 repeats.pptx
Day 1d R structures & objects: matrices and data frames.pptx
Day 1c access, select ordering copy.pptx
Day 1b R structures objects.pptx

Recently uploaded (20)

PPTX
2025 High Blood Pressure Guideline Slide Set.pptx
PDF
The TKT Course. Modules 1, 2, 3.for self study
PDF
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI Syllabus.pdf
PDF
1.Salivary gland disease.pdf 3.Bleeding and Clotting Disorders.pdf important
PDF
Journal of Dental Science - UDMY (2022).pdf
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PDF
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
PPTX
4. Diagnosis and treatment planning in RPD.pptx
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PDF
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2015).pdf
PPTX
ACFE CERTIFICATION TRAINING ON LAW.pptx
PDF
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
PDF
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
PDF
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
PDF
M.Tech in Aerospace Engineering | BIT Mesra
PDF
Lecture on Viruses: Structure, Classification, Replication, Effects on Cells,...
PPTX
Reproductive system-Human anatomy and physiology
PDF
Laparoscopic Colorectal Surgery at WLH Hospital
PPTX
pharmaceutics-1unit-1-221214121936-550b56aa.pptx
PPTX
Climate Change and Its Global Impact.pptx
2025 High Blood Pressure Guideline Slide Set.pptx
The TKT Course. Modules 1, 2, 3.for self study
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI Syllabus.pdf
1.Salivary gland disease.pdf 3.Bleeding and Clotting Disorders.pdf important
Journal of Dental Science - UDMY (2022).pdf
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
4. Diagnosis and treatment planning in RPD.pptx
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2015).pdf
ACFE CERTIFICATION TRAINING ON LAW.pptx
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
M.Tech in Aerospace Engineering | BIT Mesra
Lecture on Viruses: Structure, Classification, Replication, Effects on Cells,...
Reproductive system-Human anatomy and physiology
Laparoscopic Colorectal Surgery at WLH Hospital
pharmaceutics-1unit-1-221214121936-550b56aa.pptx
Climate Change and Its Global Impact.pptx

Day 5a iteration and functions if().pptx

  • 1. Iteration and functions: if() Day 5a - Introduction to R for Life Sciences
  • 2. if() (and else) if( some.condition ) { # do stuff } some.condition is simply a single-valued logical. As with functions, and for-loops: indent, and use curly braces if ( some.condition) { # do stuff } else { # do other stuff }
  • 3. if Conditions often look like if( a > b ) { … } But you can also use logicals: if ( print.to.file ) { … } Never write: if (print.to.file == TRUE) { … } Nor: if ( adjust.pvalues == FALSE ) { … }. Instead, write if (! adjust.pvalues) { … }
  • 4. Condition must be a single value if (big.vector) { do.stuff() } Warning message: In if (big.vector) { do.stuff() } : the condition has length > 1 and only the first element will be used Use aggregate functions such as any() or all() Inside if(), prefer && and || for logical AND and logical OR (as opposed to & and | )
  • 5. if() statement inside for-loop Avoid using the for-loop variable in an if-condition for(g in genes) { if ( data[g, 'strand'] == '-') { data[g, 'len' ] <- -data[g, 'len'] } } It’s often a sign that things can be simplified using vector notation: rev <- data[genes, 'strand'] == '-' data[rev , 'len' ] <- -data[rev, 'len' ]
  • 7. && and || They work on only the first element (and silently ignore the rest) They short-circuit: only as many as needed are evaluated: if( is.null(s) || s=="" ) { # double bar stop("string missing") } There may be no first element: > s<-NULL > s=="" logical(0) > if( is.null(s) | s=="" ) { # single bar stop("string missing") } Error in if (is.null(s) | s == "") { : argument is of length zero
  • 8. The triple-dot The triple dot (…) collects ‘the rest’ of the arguments Inside the function, this ‘rest’ can be passed on to other calls (provided those functions take triple-dot arguments) Warns about arguments that never get used This magically endows your function with extra arguments Often used for plotting functions: main, sub, xlab,ylab, xlim, ylim, ...
  • 9. Example my.plot <- function(x, ...) { plot(density(x), ...) rug(x, ...) } my.plot(x, main="slx5", xlab="M", col="red", xlim=c(-4,4), lwd=2, ticksize= -0.02) Warning messages: 1: In plot.window(...) : "ticksize" is not a graphical parameter 2: In plot.xy(xy, type, ...) : "ticksize" is not a graphical parameter 3: In axis(side = side, at = at, labels = labels, ...) : "ticksize" is not a graphical parameter 4: In axis(side = side, at = at, labels = labels, ...) : "ticksize" is not a graphical parameter 5: In box(...) : "ticksize" is not a graphical parameter 6: In title(...) : "ticksize" is not a graphical parameter