SlideShare uma empresa Scribd logo
1 de 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)
}

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 

Último (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

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