SlideShare a Scribd company logo
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

PDF
Day 4a iteration and functions.pptx
Adrien Melquiond
 
PDF
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
PDF
11 1. multi-dimensional array eng
웅식 전
 
PDF
Cheat sheet python3
sxw2k
 
PDF
Dplyr and Plyr
Paul Richards
 
PDF
10. Getting Spatial
FAO
 
PDF
Python3 cheatsheet
Gil Cohen
 
PPTX
Sharbani bhattacharya sacta 2014
Sharbani Bhattacharya
 
Day 4a iteration and functions.pptx
Adrien Melquiond
 
Day 1c access, select ordering copy.pptx
Adrien Melquiond
 
11 1. multi-dimensional array eng
웅식 전
 
Cheat sheet python3
sxw2k
 
Dplyr and Plyr
Paul Richards
 
10. Getting Spatial
FAO
 
Python3 cheatsheet
Gil Cohen
 
Sharbani bhattacharya sacta 2014
Sharbani Bhattacharya
 

What's hot (20)

PDF
NumPy Refresher
Lukasz Dobrzanski
 
PDF
Numpy tutorial(final) 20160303
Namgee Lee
 
DOCX
CLUSTERGRAM
Dr. Volkan OBAN
 
PDF
11. Linear Models
FAO
 
PDF
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
Subhajit Sahu
 
DOCX
Basic Calculus in R.
Dr. Volkan OBAN
 
PDF
Python For Data Science Cheat Sheet
Karlijn Willems
 
PDF
Numpy python cheat_sheet
Nishant Upadhyay
 
PDF
Data Clustering with R
Yanchang Zhao
 
PDF
C Language Lecture 10
Shahzaib Ajmal
 
PPTX
130717666736980000
Tanzeel Ahmad
 
DOCX
Advanced Data Visualization in R- Somes Examples.
Dr. Volkan OBAN
 
PDF
13. Cubist
FAO
 
PDF
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
PDF
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
 
PDF
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Dr. Volkan OBAN
 
PDF
Clustering and Visualisation using R programming
Nixon Mendez
 
PDF
Python 2.5 reference card (2009)
gekiaruj
 
PDF
6. Vectors – Data Frames
FAO
 
PDF
Distributive Property 7th
jscafidi7
 
NumPy Refresher
Lukasz Dobrzanski
 
Numpy tutorial(final) 20160303
Namgee Lee
 
CLUSTERGRAM
Dr. Volkan OBAN
 
11. Linear Models
FAO
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
Subhajit Sahu
 
Basic Calculus in R.
Dr. Volkan OBAN
 
Python For Data Science Cheat Sheet
Karlijn Willems
 
Numpy python cheat_sheet
Nishant Upadhyay
 
Data Clustering with R
Yanchang Zhao
 
C Language Lecture 10
Shahzaib Ajmal
 
130717666736980000
Tanzeel Ahmad
 
Advanced Data Visualization in R- Somes Examples.
Dr. Volkan OBAN
 
13. Cubist
FAO
 
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
 
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Dr. Volkan OBAN
 
Clustering and Visualisation using R programming
Nixon Mendez
 
Python 2.5 reference card (2009)
gekiaruj
 
6. Vectors – Data Frames
FAO
 
Distributive Property 7th
jscafidi7
 
Ad

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

PPTX
A quick introduction to R
Angshuman Saha
 
PPTX
R
exsuns
 
PPTX
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Vyacheslav Arbuzov
 
PPTX
R programming language
Alberto Minetti
 
PPT
Learn Matlab
Abd El Kareem Ahmed
 
PDF
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
PDF
A common fixed point theorem for two random operators using random mann itera...
Alexander Decker
 
PDF
TENSOR DECOMPOSITION WITH PYTHON
André Panisson
 
PDF
Table of Useful R commands.
Dr. Volkan OBAN
 
PDF
BUilt in Functions and Simple programs in R.pdf
karthikaparthasarath
 
PPT
haskell5.ppt is a marketing document lol
dopointt
 
PPTX
R Language Introduction
Khaled Al-Shamaa
 
PDF
Python grass
Margherita Di Leo
 
PPTX
Oh Composable World!
Brian Lonsdorf
 
PDF
Артём Акуляков - F# for Data Analysis
SpbDotNet Community
 
PDF
Response Surface in Tensor Train format for Uncertainty Quantification
Alexander Litvinenko
 
PDF
Answers withexplanations
Gopi Saiteja
 
KEY
Haskellで学ぶ関数型言語
ikdysfm
 
PPTX
Smart Multitask Bregman Clustering
Venkat Sai Sharath Mudhigonda
 
PDF
The Ring programming language version 1.8 book - Part 28 of 202
Mahmoud Samir Fayed
 
A quick introduction to R
Angshuman Saha
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Vyacheslav Arbuzov
 
R programming language
Alberto Minetti
 
Learn Matlab
Abd El Kareem Ahmed
 
Declare Your Language: Transformation by Strategic Term Rewriting
Eelco Visser
 
A common fixed point theorem for two random operators using random mann itera...
Alexander Decker
 
TENSOR DECOMPOSITION WITH PYTHON
André Panisson
 
Table of Useful R commands.
Dr. Volkan OBAN
 
BUilt in Functions and Simple programs in R.pdf
karthikaparthasarath
 
haskell5.ppt is a marketing document lol
dopointt
 
R Language Introduction
Khaled Al-Shamaa
 
Python grass
Margherita Di Leo
 
Oh Composable World!
Brian Lonsdorf
 
Артём Акуляков - F# for Data Analysis
SpbDotNet Community
 
Response Surface in Tensor Train format for Uncertainty Quantification
Alexander Litvinenko
 
Answers withexplanations
Gopi Saiteja
 
Haskellで学ぶ関数型言語
ikdysfm
 
Smart Multitask Bregman Clustering
Venkat Sai Sharath Mudhigonda
 
The Ring programming language version 1.8 book - Part 28 of 202
Mahmoud Samir Fayed
 
Ad

More from Adrien Melquiond (9)

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

Recently uploaded (20)

PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
CDH. pptx
AneetaSharma15
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
CDH. pptx
AneetaSharma15
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 

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) }