SlideShare a Scribd company logo
1 of 9
Iteration and functions: for-loops
Day 4 - Introduction to R for Life Sciences
Copy paste is evil (a.k.a Don’t Repeat Yourself)
plot(density(M[ , "msn2_del"]),
main="msn2_del")
rug(M[ , "msn2_del"])
plot(density(M[ , "ssn6_del"]),
main="ssn6_del")
rug(M[ , "ssn6_del"])
plot(density(M[ , "ctr9_del"]),
main="ctr9_del")
rug(M[ , "ctr9_del"])
Refactoring ....
plot(density(M[ , "msn2_del"]),
main="msn2_del")
rug(M[ , "msn2_del"])
plot(density(M[ , "ssn6_del"]),
main="ssn6_del")
rug(M[ , "ssn6_del"])
plot(density(M[ , "ctr9_del"]),
main="ctr9_del")
rug(M[ , "ctr9_del"])
my.plot <- function(name) {
plot(density(M[ , name]),
main=name)
rug(M[ , name])
NULL
}
my.plot("msn2_del")
my.plot("ssn6_del")
my.plot("ctr9_del")
wrong: right:
my.plot <- function(name) {
plot(density(M[ , name]),
main=name)
rug(M[ , name])
}
# M is defined outside my.plot
my.plot("msn2_del")
my.plot("ssn6_del")
my.plot("ctr9_del")
# Avoid global variables; pass them in as arguments
my.plot <- function(mat, name) {
x <- mat[,name]
plot(density(x), main=name)
rug(x)
}
my.plot(M, "msn2_del")
my.plot(M, "ssn6_del")
my.plot(M, "ctr9_del")
Even less copy-pasting: for-loops
for ( some.variable in some.vector) {
cat( some.variable, “n”)
}
The statements inside the curly braces are executed as many times
as the length of some.vector, with some.variable getting each of the
values in some.vector in turn.
deletions <- c(“msn2_del”, “ssn6_del”, “ctr9_del”)
for (del in deletions) {
my.plot(M, del)
}
Iteration using for-loops
for (cutoff in c(0.001, 0.01, 0.05)) { # start of block
print.performance(data, p=cutoff) # note indentation
} # end of block
for (TF in colnames(data) ) {
txpts <- select.txpts(data, TF, k=3, limit=0.5)
network <- network.add(network, data, TF, txpts)
}
Avoid loops if you can use aggregates or apply()
# don’t:
total <- 0
for(i in 1:length(x)) {
total <- total + (x[i])^2
}
# … or:
means <- rep(NA, ncol(data))
for (col in 1:ncol(data)) {
means[col] <- mean(data[,col])
}
# do:
sum(x^2)
apply(data, 2, mean)
Accessing lists()
> lst$a
[1] 3
> lst$b
[1] 1 2 3 4 5 6 7 8 9 10
and also:
> lst[[ “a” ]]
[1] 3
> lst[[ “b” ]]
[1] 1 2 3 4 5 6 7 8 9 10
Note the double square brackets!
> name <- “a”
> lst[[ name ]]
[1] 3
> name <- “b”
> lst[[name]]
[1] 1 2 3 4 5 6 7 8 9 10
> load("TF_targets.rda")
> TF.targets
$ABF1
[1] "YPL242C" "YPL228W" "YPL179W"
"YPL159C" "YPL036W" etc.
$ACE2
[1] "YPL026C" "YPL024W" "YOR140W" etc.
$etc.
>names(TF.targets)
[1] "ABF1" "ACE2" etc.
for-loops on lists
for (TF in names(TF.targets) ) {
transcripts <- TF.targets[[ TF ]]
plot.txpt(main=TF,
hilite=transcripts)
}

More Related Content

What's hot

Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Namgee Lee
 
11. Linear Models
11. Linear Models11. Linear Models
11. Linear ModelsFAO
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat SheetKarlijn Willems
 
Data Clustering with R
Data Clustering with RData Clustering with R
Data Clustering with RYanchang Zhao
 
Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Dr. Volkan OBAN
 
13. Cubist
13. Cubist13. Cubist
13. CubistFAO
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Dr. Volkan OBAN
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programmingNixon Mendez
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
6. Vectors – Data Frames
6. Vectors – Data Frames6. Vectors – Data Frames
6. Vectors – Data FramesFAO
 
Distributive Property 7th
Distributive Property 7thDistributive Property 7th
Distributive Property 7thjscafidi7
 

What's hot (20)

NumPy Refresher
NumPy RefresherNumPy Refresher
NumPy Refresher
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
11. Linear Models
11. Linear Models11. Linear Models
11. Linear Models
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Basic Calculus in R.
Basic Calculus in R. Basic Calculus in R.
Basic Calculus in R.
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Data Clustering with R
Data Clustering with RData Clustering with R
Data Clustering with R
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.
 
13. Cubist
13. Cubist13. Cubist
13. Cubist
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
 
Clustering and Visualisation using R programming
Clustering and Visualisation using R programmingClustering and Visualisation using R programming
Clustering and Visualisation using R programming
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
6. Vectors – Data Frames
6. Vectors – Data Frames6. Vectors – Data Frames
6. Vectors – Data Frames
 
Distributive Property 7th
Distributive Property 7thDistributive Property 7th
Distributive Property 7th
 

Similar to Day 4b iteration and functions for-loops.pptx

A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to RAngshuman Saha
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavVyacheslav Arbuzov
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingEelco Visser
 
A common fixed point theorem for two random operators using random mann itera...
A common fixed point theorem for two random operators using random mann itera...A common fixed point theorem for two random operators using random mann itera...
A common fixed point theorem for two random operators using random mann itera...Alexander Decker
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONAndré Panisson
 
Table of Useful R commands.
Table of Useful R commands.Table of Useful R commands.
Table of Useful R commands.Dr. Volkan OBAN
 
BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfkarthikaparthasarath
 
Артём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data AnalysisАртём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data AnalysisSpbDotNet Community
 
Response Surface in Tensor Train format for Uncertainty Quantification
Response Surface in Tensor Train format for Uncertainty QuantificationResponse Surface in Tensor Train format for Uncertainty Quantification
Response Surface in Tensor Train format for Uncertainty QuantificationAlexander Litvinenko
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanationsGopi Saiteja
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
The Ring programming language version 1.8 book - Part 28 of 202
The Ring programming language version 1.8 book - Part 28 of 202The Ring programming language version 1.8 book - Part 28 of 202
The Ring programming language version 1.8 book - Part 28 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210Mahmoud Samir Fayed
 

Similar to Day 4b iteration and functions for-loops.pptx (20)

A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 
R
RR
R
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
 
R programming language
R programming languageR programming language
R programming language
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
A common fixed point theorem for two random operators using random mann itera...
A common fixed point theorem for two random operators using random mann itera...A common fixed point theorem for two random operators using random mann itera...
A common fixed point theorem for two random operators using random mann itera...
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHON
 
Table of Useful R commands.
Table of Useful R commands.Table of Useful R commands.
Table of Useful R commands.
 
BUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdfBUilt in Functions and Simple programs in R.pdf
BUilt in Functions and Simple programs in R.pdf
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Python grass
Python grassPython grass
Python grass
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
Артём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data AnalysisАртём Акуляков - F# for Data Analysis
Артём Акуляков - F# for Data Analysis
 
Response Surface in Tensor Train format for Uncertainty Quantification
Response Surface in Tensor Train format for Uncertainty QuantificationResponse Surface in Tensor Train format for Uncertainty Quantification
Response Surface in Tensor Train format for Uncertainty Quantification
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Smart Multitask Bregman Clustering
Smart Multitask Bregman ClusteringSmart Multitask Bregman Clustering
Smart Multitask Bregman Clustering
 
The Ring programming language version 1.8 book - Part 28 of 202
The Ring programming language version 1.8 book - Part 28 of 202The Ring programming language version 1.8 book - Part 28 of 202
The Ring programming language version 1.8 book - Part 28 of 202
 
The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210
 

More from Adrien Melquiond

Day 1a welcome introduction
Day 1a   welcome   introductionDay 1a   welcome   introduction
Day 1a welcome introductionAdrien Melquiond
 
Day 5b statistical functions.pptx
Day 5b   statistical functions.pptxDay 5b   statistical functions.pptx
Day 5b statistical functions.pptxAdrien Melquiond
 
Day 5a iteration and functions if().pptx
Day 5a   iteration and functions  if().pptxDay 5a   iteration and functions  if().pptx
Day 5a iteration and functions if().pptxAdrien Melquiond
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptxAdrien Melquiond
 
Day 1b R structures objects.pptx
Day 1b   R structures   objects.pptxDay 1b   R structures   objects.pptx
Day 1b R structures objects.pptxAdrien Melquiond
 

More from Adrien Melquiond (9)

Day 1a welcome introduction
Day 1a   welcome   introductionDay 1a   welcome   introduction
Day 1a welcome introduction
 
R course ggplot2
R course   ggplot2R course   ggplot2
R course ggplot2
 
Day 5b statistical functions.pptx
Day 5b   statistical functions.pptxDay 5b   statistical functions.pptx
Day 5b statistical functions.pptx
 
Day 5a iteration and functions if().pptx
Day 5a   iteration and functions  if().pptxDay 5a   iteration and functions  if().pptx
Day 5a iteration and functions if().pptx
 
Day 3 plotting.pptx
Day 3   plotting.pptxDay 3   plotting.pptx
Day 3 plotting.pptx
 
Day 2b i/o.pptx
Day 2b   i/o.pptxDay 2b   i/o.pptx
Day 2b i/o.pptx
 
Day 2 repeats.pptx
Day 2 repeats.pptxDay 2 repeats.pptx
Day 2 repeats.pptx
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptx
 
Day 1b R structures objects.pptx
Day 1b   R structures   objects.pptxDay 1b   R structures   objects.pptx
Day 1b R structures objects.pptx
 

Recently uploaded

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 

Recently uploaded (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Day 4b iteration and functions for-loops.pptx

  • 1. Iteration and functions: for-loops Day 4 - Introduction to R for Life Sciences
  • 2. Copy paste is evil (a.k.a Don’t Repeat Yourself) plot(density(M[ , "msn2_del"]), main="msn2_del") rug(M[ , "msn2_del"]) plot(density(M[ , "ssn6_del"]), main="ssn6_del") rug(M[ , "ssn6_del"]) plot(density(M[ , "ctr9_del"]), main="ctr9_del") rug(M[ , "ctr9_del"])
  • 3. Refactoring .... plot(density(M[ , "msn2_del"]), main="msn2_del") rug(M[ , "msn2_del"]) plot(density(M[ , "ssn6_del"]), main="ssn6_del") rug(M[ , "ssn6_del"]) plot(density(M[ , "ctr9_del"]), main="ctr9_del") rug(M[ , "ctr9_del"]) my.plot <- function(name) { plot(density(M[ , name]), main=name) rug(M[ , name]) NULL } my.plot("msn2_del") my.plot("ssn6_del") my.plot("ctr9_del")
  • 4. wrong: right: my.plot <- function(name) { plot(density(M[ , name]), main=name) rug(M[ , name]) } # M is defined outside my.plot my.plot("msn2_del") my.plot("ssn6_del") my.plot("ctr9_del") # Avoid global variables; pass them in as arguments my.plot <- function(mat, name) { x <- mat[,name] plot(density(x), main=name) rug(x) } my.plot(M, "msn2_del") my.plot(M, "ssn6_del") my.plot(M, "ctr9_del")
  • 5. Even less copy-pasting: for-loops for ( some.variable in some.vector) { cat( some.variable, “n”) } The statements inside the curly braces are executed as many times as the length of some.vector, with some.variable getting each of the values in some.vector in turn. deletions <- c(“msn2_del”, “ssn6_del”, “ctr9_del”) for (del in deletions) { my.plot(M, del) }
  • 6. Iteration using for-loops for (cutoff in c(0.001, 0.01, 0.05)) { # start of block print.performance(data, p=cutoff) # note indentation } # end of block for (TF in colnames(data) ) { txpts <- select.txpts(data, TF, k=3, limit=0.5) network <- network.add(network, data, TF, txpts) }
  • 7. Avoid loops if you can use aggregates or apply() # don’t: total <- 0 for(i in 1:length(x)) { total <- total + (x[i])^2 } # … or: means <- rep(NA, ncol(data)) for (col in 1:ncol(data)) { means[col] <- mean(data[,col]) } # do: sum(x^2) apply(data, 2, mean)
  • 8. Accessing lists() > lst$a [1] 3 > lst$b [1] 1 2 3 4 5 6 7 8 9 10 and also: > lst[[ “a” ]] [1] 3 > lst[[ “b” ]] [1] 1 2 3 4 5 6 7 8 9 10 Note the double square brackets! > name <- “a” > lst[[ name ]] [1] 3 > name <- “b” > lst[[name]] [1] 1 2 3 4 5 6 7 8 9 10
  • 9. > load("TF_targets.rda") > TF.targets $ABF1 [1] "YPL242C" "YPL228W" "YPL179W" "YPL159C" "YPL036W" etc. $ACE2 [1] "YPL026C" "YPL024W" "YOR140W" etc. $etc. >names(TF.targets) [1] "ABF1" "ACE2" etc. for-loops on lists for (TF in names(TF.targets) ) { transcripts <- TF.targets[[ TF ]] plot.txpt(main=TF, hilite=transcripts) }