R

© All Rights Reserved

1 views

R

© All Rights Reserved

- Javascript Referance - Jan Zumwalt
- Python Programming.docx
- IT SBA CXC Question 2 Markscheme Mona High School 2011
- Scientific En
- lecturenotes6.pptx
- MELJUN CORTES Programming Languages Statements
- Turbo Basic Command List
- Ds loop with Tx
- C - Quick Guide
- Unit 4
- PY Unit III
- C Plus Plus
- Java Examples1
- OR_ch7
- Flowchart Symbols
- cheatsheet_2_05_2011
- Ch 16
- Functions Basics 2
- Bait Apc
- material on java and adacance rules book.pdf

You are on page 1of 13

Anders Stockmarr, Kasper Kristensen, Anders Nielsen

Loops in R

I In R the for loop is used perform a task for each element in a set.

I Example:

I Given a set of integers:

> 1:3

[1] 1 2 3

I Let a variable i run through the set and print i + i:

> for(i in 1:3) {

+ cat(i, "+", i, "=", i+i, "\n")

+ }

1 + 1 = 2

2 + 2 = 4

3 + 3 = 6

I The sequence to loop through is not limited to a vector of integers. For

example, we could let a variable run through a list, data.frame or matrix.

I Example:

I > d <- data.frame(a = 1:2, b=2:3)

I Print column sums of d:

> for(x in d) {

+ cat("Column sum:", sum(x), "\n")

+ }

Column sum: 3

Column sum: 5

Flow Control: if and if else statements

I if(cond) expr:

> for(i in 1:3){

+ if (i==2) cat("This index is even:","\n")

+ cat(i,"\n")

+ }

1

This index is even:

2

3

I if(cond) cond.expr else alt.expr:

> for(i in 1:3){

+ if (i==2) cat("The index is 2","\n") else

+ cat("The index is not 2","\n")

+ }

The index is not 2

The index is 2

The index is not 2

Flow charts for if and if else statements

Break?

Test expr. Test expr.

TRUE

1st body 2nd body

Body of if of if else of if else

While and repeat loops

I while(cond) expr

I repeat expr

Flow controllers:

I next: Halts the execution of the current iteration of the loop and advances

to the next

I break: Exits the loop

Flow charts for repeat and while loops

Body of Yes

Break? Exit while loop

loop

No

No Body of

Break?

loop

Yes

While loop example

> y<-abs(rnorm(1000)) # simulated part size

> i<-0 # index of parts

> # loop:

> while(k<3 & i<1000){

+ i<-i+1

+ temp<-y[i]

+ k<-k+(temp>2)

+ }

> rm(temp)

> i

[1] 42

Repeat loop example

> eye.colors<-c("brown","blue","green","yellow","grey")

> eyecolor<-data.frame(personId=1:100,color=

+ sample(eye.colors,100,rep=T))

> i<-0

> list.of.ids<-numeric(0) # patient ID list

> #loop:

> repeat {

+ i<-i+1

+ if(eyecolor$color[i]=="yellow" |

+ eyecolor$color[i]=="blue") next

+ list.of.ids<-c(list.of.ids,eyecolor$personId[i])

+ if(i==100 | length(list.of.ids)==20) break

+ }

> list.of.ids

[1] 5 6 7 9 10 11 12 14 15 18 19 20 21 22 23 24 25 28

[19] 29 30

Loops and run times

When the amount of data is large, loops can significantly increase run time:

> y<-matrix(rnorm(1000000),nrow=1000)

> z<-0*y

> time1<-as.numeric(Sys.time())

> #loop:

> for(i in 1:1000){

+ for(j in 1:1000){

+ z[i,j]<-y[i,j]^2

+ }

+ }

> time2<-as.numeric(Sys.time())

> # using object form in R:

> z<-y^2

> time3<-as.numeric(Sys.time())

> # run time increase factor:

> (time2-time1)/(time3-time2)

[1] Inf

lapply() and sapply()

I The lapply() and sapply() function apply functions to the input.

I The lapply() and sapply() are similar, except that:

I The output from lapply() is a list;

I The output from sapply() is a vector or a matrix.

lapply() and sapply examples

> my.data<-data.frame(data1=rnorm(10),data2=rnorm(10),data3=rnorm(10))

> lapply(my.data,sum)

$data1

[1] 3.189681

$data2

[1] 2.711566

$data3

[1] -3.247268

> sapply(my.data,sum)

data1 data2 data3

3.189681 2.711566 -3.247268

lapply() and sapply() examples

> A<-matrix(1:9,nrow=3);B<-matrix(1:16,nrow=4);C=matrix(1:8,nrow=4)

> my.list<-list(A=A,B=B,C=C); my.list

$A

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

$B

[,1] [,2] [,3] [,4]

[1,] 1 5 9 13

[2,] 2 6 10 14

[3,] 3 7 11 15

[4,] 4 8 12 16

$C

[,1] [,2]

[1,] 1 5

[2,] 2 6

[3,] 3 7

[4,] 4 8

lapply() and sapply() examples

Now lets suppose that we want to extract the second column of each of these

matrices. We can do this with the square bracket function:

> lapply(my.list,"[",,2)

$A

[1] 4 5 6

$B

[1] 5 6 7 8

$C

[1] 5 6 7 8

- Javascript Referance - Jan ZumwaltUploaded byjwzumwalt
- Python Programming.docxUploaded byBad Man
- IT SBA CXC Question 2 Markscheme Mona High School 2011Uploaded byFrank King Kai Hyman
- Scientific EnUploaded byFirzan
- lecturenotes6.pptxUploaded byKevin Paxson
- MELJUN CORTES Programming Languages StatementsUploaded byMELJUN CORTES, MBA,MPA
- Turbo Basic Command ListUploaded bykuashask2
- Ds loop with TxUploaded bySai Vishnu Vardhan
- C - Quick GuideUploaded byJeRome Ballena
- Unit 4Uploaded byKiran Reddy
- PY Unit IIIUploaded byDennis Ebenezer Dhanaraj
- C Plus PlusUploaded byLakshmi Rao
- Java Examples1Uploaded bySritanvi
- Flowchart SymbolsUploaded byJayson Nosyaj
- cheatsheet_2_05_2011Uploaded byQuang Sinh
- Ch 16Uploaded byjeraguilon
- OR_ch7Uploaded byKavi Yarasi
- Functions Basics 2Uploaded byravitejabavandla
- Bait ApcUploaded byanystars
- material on java and adacance rules book.pdfUploaded byShaan
- CS SET IIIUploaded byAishwarya Babu
- Lec 18 WhileUploaded byFay Fernandez-Cantuangco
- CProgrammingClass-2Uploaded byvenkeeku
- fastCUploaded byOmar Abderrahim
- MIT6 004s09 Study c OverviewUploaded byAsish Kolanu
- Q-2Uploaded bysubhashissohail
- t05BProgramControlAlgorithmsUploaded byPavitha Guru G
- Bad Career 3Uploaded bydnlgrur
- Lightning Lab - Programming Block Hints (1)Uploaded byseagull70
- Drdo SampleUploaded byArghya Guha

- Case_ University Health Services_ Walk-In Clinic Essay _ BartlebyUploaded byGuilherme
- Dynamic Bayesian Network _ Parameter Learning _ RUploaded byGuilherme
- dbn dynamic bayes R - Pesquisa Google.pdfUploaded byGuilherme
- Getting StartedUploaded byXenogenic Medusa
- IntroductionUploaded byMdMorshedulHaque
- Weo Update July 2017Uploaded byGuilherme
- SSRN-id1283413Uploaded byGuilherme
- EViews 6 Command Ref.pdfUploaded bydiska
- Confederate Pulp and PaperUploaded byShreeraj Pawar

- Optimization of the Preheater Cyclone Separators Used in the Cement IndustryUploaded bysaeedhoseini
- UWB8Uploaded bytqminh25
- 1000 Tech. InterviewQuestionsUploaded bySun Surya
- Bitcoin: A Primer for PolicymakersUploaded byMercatus Center at George Mason University
- Affidavit of Authenticity of the CCTV Video Footages 06March2018.docxUploaded byLorenzo Marvin Reyes
- 0824a779.pdfUploaded byPradana Ananda Raharja
- LinearUploaded byBon Cyrell Villacarlos Plazos
- c and c++ notesUploaded bySean Norman
- Penlon Prima Sp2 BookletUploaded bypatrick1009
- SAP License QUICK GUIDE.docxUploaded byAnonymous h19lskP2UV
- Uhde Brochures PDF en 18Uploaded bygeocotton
- TR-029.pdfUploaded byst3lios
- Rethinking the Systems Engineering Process in Light of Design Thinking \Uploaded byjwpaprk1
- SystemTap - Instrumenting the Linux Kernel for Analyzing Performance and Functional Problems (IBM, April 2009)Uploaded byEledel
- Stat230 S2010 Course NotesUploaded byThierry Lusetti
- Eiken2006-1.docxUploaded byBojana
- The Naked Facts 2H2010.2Uploaded byadammichaelc
- Test Driven Development Using Flash Builder 4 and FlexUnitUploaded byCarlos Amorim
- Tactical ExploitationUploaded bySpyDr ByTe
- GP Workbench Manual Technical ManualUploaded byPatrick Catana Gnudi
- ECE 271 Introduction to Telecommunication Networks_LECTURE (1)Uploaded byBhagaban Das
- 116Uploaded byNikhil Jain
- Transportation ModelsUploaded byBehbehlynn
- ENV 1997-2-2000Uploaded byCatalin Bogdan Chirvasa
- Cygwin x User GuideUploaded byprachanyouetc
- mis unit 2Uploaded byJaspal Singh Virk
- bio_imp.pdfUploaded byFish Komokust
- Doing Business in Bangladesh-A Country GuideUploaded byShahriar Ahmed Shaikat
- Professional 4 EngUploaded byprofisec
- Asterisk ServerUploaded byFish Bone