SlideShare a Scribd company logo
1 of 28
Download to read offline
Stat405       Functions & for loops


                            Hadley Wickham
Monday, 21 September 2009
1. Changes to homework
               2. Function structure and calling
                  conventions
               3. Practice writing functions
               4. For loops



Monday, 21 September 2009
Homework changes
                   Figuring out the problem isn’t as easy as
                   I’d thought, so we’ll cover it in class
                   today.
                   Due next Wednesday, with some TBA
                   function drills.
                   Pay attention to the style guide!



Monday, 21 September 2009
Basic structure
                   • Name
                   • Input arguments
                        • Names/positions
                        • Defaults
                   • Body
                   • Output (final result)


Monday, 21 September 2009
calculate_prize <- function(windows) {
       payoffs <- c("DD" = 800, "7" = 80, "BBB" = 40,
         "BB" = 25, "B" = 10, "C" = 10, "0" = 0)

         same <- length(unique(windows)) == 1
         allbars <- all(windows %in% c("B", "BB", "BBB"))

         if (same) {
           prize <- payoffs[windows[1]]
         } else if (allbars) {
           prize <- 5
         } else {
           cherries <- sum(windows == "C")
           diamonds <- sum(windows == "DD")

             prize <- c(0, 2, 5)[cherries + 1] *
               c(1, 2, 4)[diamonds + 1]
         }
         prize
     }

Monday, 21 September 2009
calculate_prize <- function(windows) {
       payoffs <- c("DD" = 800, "7" = 80, "BBB" = 40,
                                arguments
        name = 25, "B" = 10, "C" = 10, "0" = 0)
         "BB"

         same <- length(unique(windows)) == 1
         allbars <- all(windows %in% c("B", "BB", "BBB"))

      if (same) {
        prize <- payoffs[windows[1]]
      } else if (allbars) {
        prize <- 5
      } else {
  always indent <- sum(windows == "C")
        cherries
     inside {}! <- sum(windows == "DD")
        diamonds

             prize <- c(0, 2, 5)[cherries + 1] *
               c(1, 2, 4)[diamonds + 1]
         }
         prize
     }
         last value in function is result
Monday, 21 September 2009
mean <- function(x) {
       sum(x) / length(x)
     }
     mean(1:10)

     mean <- function(x, na.rm = TRUE) {
       if (na.rm) x <- x[!is.na(x)]
       sum(x) / length(x)
     }
     mean(c(NA, 1:9))




Monday, 21 September 2009
mean <- function(x) {
       sum(x) / length(x)
     }
     mean(1:10)
                                 default value

     mean <- function(x, na.rm = TRUE) {
       if (na.rm) x <- x[!is.na(x)]
       sum(x) / length(x)
     }
     mean(c(NA, 1:9))




Monday, 21 September 2009
# Function: mean
     str(mean)
     mean

     args(mean)
     formals(mean)
     body(mean)




Monday, 21 September 2009
Function arguments
                   Every function argument has a name and
                   a position. When calling, matches exact
                   name, then partial name, then position.
                   Rule of thumb: for common functions,
                   position based matching is ok for required
                   arguments. Otherwise use names
                   (abbreviated as long as clear).


Monday, 21 September 2009
mean(c(NA, 1:9), na.rm = T)

     # Confusing in this case, but often saves typing
     mean(c(NA, 1:9), na = T)

     # Generally don't need to name all arguments
     mean(x = c(NA, 1:9), na.rm = T)

     # Unusual orders best avoided, but
     # illustrate the principle
     mean(na.rm = T, c(NA, 1:9))
     mean(na = T, c(NA, 1:9))


Monday, 21 September 2009
# Overkill
     qplot(x = price, y = carat, data = diamonds)

     # Don't need to supply defaults
     mean(c(NA, 1:9), na.rm = F)

     # Need to remember too much about mean
     mean(c(NA, 1:9), , T)

     # Don't abbreviate too much!
     mean(c(NA, 1:9), n = T)



Monday, 21 September 2009
f <- function(a = 1, abcd = 1, abdd = 1) {
       print(a)
       print(abcd)
       print(abdd)
     }

     f(a = 5)
     f(ab = 5)
     f(abc = 5)




Monday, 21 September 2009
Your turn
                   Write a function to calculate the variance
                   of a vector. Write a function to calculate
                   the covariance of two vectors.
                   Make sure each has a na.rm argument.
                   Write functions in your text editor, then
                   copy into R.



Monday, 21 September 2009
Strategy
                   Always want to start simple: start with
                   test values and get the body of the
                   function working first.
                   Check each step as you go.
                   Don’t try and do too much at once!
                   Create the function once everything
                   works.


Monday, 21 September 2009
x <- 1:10
     sum((x - mean(x)) ^ 2)

     var <- function(x) sum((x - mean(x)) ^ 2)

     x <- c(1:10, NA)
     var(x)

     na.rm <- TRUE
     if (na.rm) {
       x <- x[!is.na(x)]
     }
     var <- function(x, na.rm = F) {
       if (na.rm) {
         x <- x[!is.na(x)]
       }
       sum((x - mean(x)) ^ 2)
     }

Monday, 21 September 2009
Testing
                   Always a good idea to test your code.
                   We have a prebuilt set of test cases: the
                   prize column in slots.csv
                   So for each row in slots.csv, we need to
                   calculate the prize and compare it to the
                   actual. (Hopefully they will be same!)



Monday, 21 September 2009
For loops
               for(value in 1:10) {
                 print(value)
               }

               cuts <- levels(diamonds$cut)
               for(cut in cuts) {
                 selected <- diamonds$price[diamonds$cut == cut]
                 print(mean(selected))
               }
               # Have to do something with output!



Monday, 21 September 2009
# Common pattern: create object for output,
     # then fill with results

     cuts <- levels(diamonds$cut)
     means <- vector("numeric", length(cuts))

     for(i in seq_along(cuts)) {
       sub <- diamonds[diamonds$cut == cuts[i], ]
       means[i] <- mean(sub$price)
     }

     # We will learn more sophisticated ways to do this
     # later on, but this is the most explicit


Monday, 21 September 2009
# Common pattern: create object for output,
     # then fill with results

     cuts <- levels(diamonds$cut)
     means <- vector("numeric", length(cuts))

     for(i in seq_along(cuts)) { Why use i and not cut?
       sub <- diamonds[diamonds$cut == cuts[i], ]
       means[i] <- mean(sub$price)
     }

     # We will learn more sophisticated ways to do this
     # later on, but this is the most explicit


Monday, 21 September 2009
seq_len(5)
     seq_len(10)
     n <- 10
     seq_len(10)

     seq_along(1:10)
     seq_along(1:10 * 2)




Monday, 21 September 2009
Your turn


                   For each diamond colour, calculate the
                   median price and carat size




Monday, 21 September 2009
colours <- levels(diamonds$color)
     n <- length(colours)
     mprice <- rep(NA, n)
     mcarat <- rep(NA, n)

     for(i in seq_len(n)) {
       set <- diamonds[diamonds$color == colours[i], ]
       mprice[i] <- median(set$price)
       mcarat[i] <- median(set$carat)
     }

     results <- data.frame(colours, mprice, mcarat)


Monday, 21 September 2009
Back to slots...
                   For each row, calculate the prize and save
                   it, then compare calculated prize to actual
                   prize


                   Question: given a row, how can we
                   extract the slots in the right form for the
                   function?


Monday, 21 September 2009
slots <- read.csv("slots.csv")


         i <- 334
         slots[i, ]
         slots[i, 1:3]
         str(slots[i, 1:3])
         as.character(slots[i, 1:3])
         c(as.character(slots[i, 1]), as.character(slots[i, 2]),
         as.character(slots[i, 3]))


         slots <- read.csv("slots.csv", stringsAsFactors = F)
         str(slots[i, 1:3])
         as.character(slots[i, 1:3])


         calculate_prize(as.character(slots[i, 1:3]))

Monday, 21 September 2009
# Create space to put the results
     slots$check <- NA

     # For each row, calculate the prize
     for(i in seq_len(nrow(slots))) {
       w <- as.character(slots[i, 1:3])
       slots$check[i] <- calculate_prize(w)
     }

     # Check with known answers
     subset(slots, prize != prize_c)
     # Uh oh!


Monday, 21 September 2009
# Create space to put the results
     slots$check <- NA

     # For each row, calculate the prize
     for(i in seq_len(nrow(slots))) {
       w <- as.character(slots[i, 1:3])
       slots$check[i] <- calculate_prize(w)
     }

     # Check with known answers
     subset(slots, prize != prize_c)
     # Uh oh!
                             What is the problem? Think
                             about the most generalise case
Monday, 21 September 2009
DD            DD   DD   800
                                            windows <- c("DD", "C", "C")
                7           7    7    80
                                            # How can we calculate the
            BBB BBB BBB               40    # payoff?
                B           B    B    10
                C           C    C    10
            Any bar Any bar Any bar    5
                C           C    *     5
                C           *    C     5
                C           *    *     2
                 *          C    *     2    DD doubles any winning
                                            combination. Two DD
                 *          *    C     2    quadruples. DD is wild
Monday, 21 September 2009

More Related Content

Viewers also liked

R Workshop for Beginners
R Workshop for BeginnersR Workshop for Beginners
R Workshop for BeginnersMetamarkets
 
Why R? A Brief Introduction to the Open Source Statistics Platform
Why R? A Brief Introduction to the Open Source Statistics PlatformWhy R? A Brief Introduction to the Open Source Statistics Platform
Why R? A Brief Introduction to the Open Source Statistics PlatformSyracuse University
 
Intro to R statistic programming
Intro to R statistic programming Intro to R statistic programming
Intro to R statistic programming Bryan Downing
 
Building a scalable data science platform with R
Building a scalable data science platform with RBuilding a scalable data science platform with R
Building a scalable data science platform with RRevolution Analytics
 
R language tutorial
R language tutorialR language tutorial
R language tutorialDavid Chiu
 
An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)Dataspora
 

Viewers also liked (10)

R Workshop for Beginners
R Workshop for BeginnersR Workshop for Beginners
R Workshop for Beginners
 
Why R? A Brief Introduction to the Open Source Statistics Platform
Why R? A Brief Introduction to the Open Source Statistics PlatformWhy R? A Brief Introduction to the Open Source Statistics Platform
Why R? A Brief Introduction to the Open Source Statistics Platform
 
Intro to R statistic programming
Intro to R statistic programming Intro to R statistic programming
Intro to R statistic programming
 
R learning by examples
R learning by examplesR learning by examples
R learning by examples
 
Building a scalable data science platform with R
Building a scalable data science platform with RBuilding a scalable data science platform with R
Building a scalable data science platform with R
 
R language tutorial
R language tutorialR language tutorial
R language tutorial
 
Class ppt intro to r
Class ppt intro to rClass ppt intro to r
Class ppt intro to r
 
Textmining Introduction
Textmining IntroductionTextmining Introduction
Textmining Introduction
 
An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)
 
R and Data Science
R and Data ScienceR and Data Science
R and Data Science
 

Similar to 08 Functions

Presenting Your Code
Presenting Your CodePresenting Your Code
Presenting Your Codemoto
 
optim function
optim functionoptim function
optim functionSupri Amir
 
Joint Repairs for Web Wrappers
Joint Repairs for Web WrappersJoint Repairs for Web Wrappers
Joint Repairs for Web WrappersGiorgio Orsi
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemMaithreya Chakravarthula
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfannikasarees
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In RRsquared Academy
 
Microsoft NERD Talk - R and Tableau - 2-4-2013
Microsoft NERD Talk - R and Tableau - 2-4-2013Microsoft NERD Talk - R and Tableau - 2-4-2013
Microsoft NERD Talk - R and Tableau - 2-4-2013Tanya Cashorali
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RRsquared Academy
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the worldDavid Muñoz Díaz
 
Refactoring Ruby Code
Refactoring Ruby CodeRefactoring Ruby Code
Refactoring Ruby CodeCaike Souza
 
W7 57-010126-2009-8
W7 57-010126-2009-8W7 57-010126-2009-8
W7 57-010126-2009-8OHM_Resistor
 
Visualising Big Data
Visualising Big DataVisualising Big Data
Visualising Big DataAmit Kapoor
 

Similar to 08 Functions (20)

Presenting Your Code
Presenting Your CodePresenting Your Code
Presenting Your Code
 
06 Data
06 Data06 Data
06 Data
 
03 Cleaning
03 Cleaning03 Cleaning
03 Cleaning
 
07 problem-solving
07 problem-solving07 problem-solving
07 problem-solving
 
optim function
optim functionoptim function
optim function
 
Joint Repairs for Web Wrappers
Joint Repairs for Web WrappersJoint Repairs for Web Wrappers
Joint Repairs for Web Wrappers
 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
 
11 Data Structures
11 Data Structures11 Data Structures
11 Data Structures
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support System
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdf
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 
Microsoft NERD Talk - R and Tableau - 2-4-2013
Microsoft NERD Talk - R and Tableau - 2-4-2013Microsoft NERD Talk - R and Tableau - 2-4-2013
Microsoft NERD Talk - R and Tableau - 2-4-2013
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In R
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Refactoring Ruby Code
Refactoring Ruby CodeRefactoring Ruby Code
Refactoring Ruby Code
 
W7 57-010126-2009-8
W7 57-010126-2009-8W7 57-010126-2009-8
W7 57-010126-2009-8
 
Refactoring
RefactoringRefactoring
Refactoring
 
21 Polishing
21 Polishing21 Polishing
21 Polishing
 
Visualising Big Data
Visualising Big DataVisualising Big Data
Visualising Big Data
 

More from Hadley Wickham (20)

27 development
27 development27 development
27 development
 
27 development
27 development27 development
27 development
 
24 modelling
24 modelling24 modelling
24 modelling
 
23 data-structures
23 data-structures23 data-structures
23 data-structures
 
Graphical inference
Graphical inferenceGraphical inference
Graphical inference
 
R packages
R packagesR packages
R packages
 
22 spam
22 spam22 spam
22 spam
 
21 spam
21 spam21 spam
21 spam
 
20 date-times
20 date-times20 date-times
20 date-times
 
18 cleaning
18 cleaning18 cleaning
18 cleaning
 
17 polishing
17 polishing17 polishing
17 polishing
 
16 critique
16 critique16 critique
16 critique
 
15 time-space
15 time-space15 time-space
15 time-space
 
14 case-study
14 case-study14 case-study
14 case-study
 
13 case-study
13 case-study13 case-study
13 case-study
 
12 adv-manip
12 adv-manip12 adv-manip
12 adv-manip
 
11 adv-manip
11 adv-manip11 adv-manip
11 adv-manip
 
11 adv-manip
11 adv-manip11 adv-manip
11 adv-manip
 
10 simulation
10 simulation10 simulation
10 simulation
 
10 simulation
10 simulation10 simulation
10 simulation
 

Recently uploaded

8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Peter Ward
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationAnamaria Contreras
 
8447779800, Low rate Call girls in Dwarka mor Delhi NCR
8447779800, Low rate Call girls in Dwarka mor Delhi NCR8447779800, Low rate Call girls in Dwarka mor Delhi NCR
8447779800, Low rate Call girls in Dwarka mor Delhi NCRashishs7044
 
International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...ssuserf63bd7
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in PhilippinesDavidSamuel525586
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03DallasHaselhorst
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524najka9823
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Seta Wicaksana
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Doge Mining Website
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 

Recently uploaded (20)

8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
Call Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North GoaCall Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North Goa
 
PSCC - Capability Statement Presentation
PSCC - Capability Statement PresentationPSCC - Capability Statement Presentation
PSCC - Capability Statement Presentation
 
8447779800, Low rate Call girls in Dwarka mor Delhi NCR
8447779800, Low rate Call girls in Dwarka mor Delhi NCR8447779800, Low rate Call girls in Dwarka mor Delhi NCR
8447779800, Low rate Call girls in Dwarka mor Delhi NCR
 
International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...International Business Environments and Operations 16th Global Edition test b...
International Business Environments and Operations 16th Global Edition test b...
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
Entrepreneurship lessons in Philippines
Entrepreneurship lessons in  PhilippinesEntrepreneurship lessons in  Philippines
Entrepreneurship lessons in Philippines
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 

08 Functions

  • 1. Stat405 Functions & for loops Hadley Wickham Monday, 21 September 2009
  • 2. 1. Changes to homework 2. Function structure and calling conventions 3. Practice writing functions 4. For loops Monday, 21 September 2009
  • 3. Homework changes Figuring out the problem isn’t as easy as I’d thought, so we’ll cover it in class today. Due next Wednesday, with some TBA function drills. Pay attention to the style guide! Monday, 21 September 2009
  • 4. Basic structure • Name • Input arguments • Names/positions • Defaults • Body • Output (final result) Monday, 21 September 2009
  • 5. calculate_prize <- function(windows) { payoffs <- c("DD" = 800, "7" = 80, "BBB" = 40, "BB" = 25, "B" = 10, "C" = 10, "0" = 0) same <- length(unique(windows)) == 1 allbars <- all(windows %in% c("B", "BB", "BBB")) if (same) { prize <- payoffs[windows[1]] } else if (allbars) { prize <- 5 } else { cherries <- sum(windows == "C") diamonds <- sum(windows == "DD") prize <- c(0, 2, 5)[cherries + 1] * c(1, 2, 4)[diamonds + 1] } prize } Monday, 21 September 2009
  • 6. calculate_prize <- function(windows) { payoffs <- c("DD" = 800, "7" = 80, "BBB" = 40, arguments name = 25, "B" = 10, "C" = 10, "0" = 0) "BB" same <- length(unique(windows)) == 1 allbars <- all(windows %in% c("B", "BB", "BBB")) if (same) { prize <- payoffs[windows[1]] } else if (allbars) { prize <- 5 } else { always indent <- sum(windows == "C") cherries inside {}! <- sum(windows == "DD") diamonds prize <- c(0, 2, 5)[cherries + 1] * c(1, 2, 4)[diamonds + 1] } prize } last value in function is result Monday, 21 September 2009
  • 7. mean <- function(x) { sum(x) / length(x) } mean(1:10) mean <- function(x, na.rm = TRUE) { if (na.rm) x <- x[!is.na(x)] sum(x) / length(x) } mean(c(NA, 1:9)) Monday, 21 September 2009
  • 8. mean <- function(x) { sum(x) / length(x) } mean(1:10) default value mean <- function(x, na.rm = TRUE) { if (na.rm) x <- x[!is.na(x)] sum(x) / length(x) } mean(c(NA, 1:9)) Monday, 21 September 2009
  • 9. # Function: mean str(mean) mean args(mean) formals(mean) body(mean) Monday, 21 September 2009
  • 10. Function arguments Every function argument has a name and a position. When calling, matches exact name, then partial name, then position. Rule of thumb: for common functions, position based matching is ok for required arguments. Otherwise use names (abbreviated as long as clear). Monday, 21 September 2009
  • 11. mean(c(NA, 1:9), na.rm = T) # Confusing in this case, but often saves typing mean(c(NA, 1:9), na = T) # Generally don't need to name all arguments mean(x = c(NA, 1:9), na.rm = T) # Unusual orders best avoided, but # illustrate the principle mean(na.rm = T, c(NA, 1:9)) mean(na = T, c(NA, 1:9)) Monday, 21 September 2009
  • 12. # Overkill qplot(x = price, y = carat, data = diamonds) # Don't need to supply defaults mean(c(NA, 1:9), na.rm = F) # Need to remember too much about mean mean(c(NA, 1:9), , T) # Don't abbreviate too much! mean(c(NA, 1:9), n = T) Monday, 21 September 2009
  • 13. f <- function(a = 1, abcd = 1, abdd = 1) { print(a) print(abcd) print(abdd) } f(a = 5) f(ab = 5) f(abc = 5) Monday, 21 September 2009
  • 14. Your turn Write a function to calculate the variance of a vector. Write a function to calculate the covariance of two vectors. Make sure each has a na.rm argument. Write functions in your text editor, then copy into R. Monday, 21 September 2009
  • 15. Strategy Always want to start simple: start with test values and get the body of the function working first. Check each step as you go. Don’t try and do too much at once! Create the function once everything works. Monday, 21 September 2009
  • 16. x <- 1:10 sum((x - mean(x)) ^ 2) var <- function(x) sum((x - mean(x)) ^ 2) x <- c(1:10, NA) var(x) na.rm <- TRUE if (na.rm) { x <- x[!is.na(x)] } var <- function(x, na.rm = F) { if (na.rm) { x <- x[!is.na(x)] } sum((x - mean(x)) ^ 2) } Monday, 21 September 2009
  • 17. Testing Always a good idea to test your code. We have a prebuilt set of test cases: the prize column in slots.csv So for each row in slots.csv, we need to calculate the prize and compare it to the actual. (Hopefully they will be same!) Monday, 21 September 2009
  • 18. For loops for(value in 1:10) { print(value) } cuts <- levels(diamonds$cut) for(cut in cuts) { selected <- diamonds$price[diamonds$cut == cut] print(mean(selected)) } # Have to do something with output! Monday, 21 September 2009
  • 19. # Common pattern: create object for output, # then fill with results cuts <- levels(diamonds$cut) means <- vector("numeric", length(cuts)) for(i in seq_along(cuts)) { sub <- diamonds[diamonds$cut == cuts[i], ] means[i] <- mean(sub$price) } # We will learn more sophisticated ways to do this # later on, but this is the most explicit Monday, 21 September 2009
  • 20. # Common pattern: create object for output, # then fill with results cuts <- levels(diamonds$cut) means <- vector("numeric", length(cuts)) for(i in seq_along(cuts)) { Why use i and not cut? sub <- diamonds[diamonds$cut == cuts[i], ] means[i] <- mean(sub$price) } # We will learn more sophisticated ways to do this # later on, but this is the most explicit Monday, 21 September 2009
  • 21. seq_len(5) seq_len(10) n <- 10 seq_len(10) seq_along(1:10) seq_along(1:10 * 2) Monday, 21 September 2009
  • 22. Your turn For each diamond colour, calculate the median price and carat size Monday, 21 September 2009
  • 23. colours <- levels(diamonds$color) n <- length(colours) mprice <- rep(NA, n) mcarat <- rep(NA, n) for(i in seq_len(n)) { set <- diamonds[diamonds$color == colours[i], ] mprice[i] <- median(set$price) mcarat[i] <- median(set$carat) } results <- data.frame(colours, mprice, mcarat) Monday, 21 September 2009
  • 24. Back to slots... For each row, calculate the prize and save it, then compare calculated prize to actual prize Question: given a row, how can we extract the slots in the right form for the function? Monday, 21 September 2009
  • 25. slots <- read.csv("slots.csv") i <- 334 slots[i, ] slots[i, 1:3] str(slots[i, 1:3]) as.character(slots[i, 1:3]) c(as.character(slots[i, 1]), as.character(slots[i, 2]), as.character(slots[i, 3])) slots <- read.csv("slots.csv", stringsAsFactors = F) str(slots[i, 1:3]) as.character(slots[i, 1:3]) calculate_prize(as.character(slots[i, 1:3])) Monday, 21 September 2009
  • 26. # Create space to put the results slots$check <- NA # For each row, calculate the prize for(i in seq_len(nrow(slots))) { w <- as.character(slots[i, 1:3]) slots$check[i] <- calculate_prize(w) } # Check with known answers subset(slots, prize != prize_c) # Uh oh! Monday, 21 September 2009
  • 27. # Create space to put the results slots$check <- NA # For each row, calculate the prize for(i in seq_len(nrow(slots))) { w <- as.character(slots[i, 1:3]) slots$check[i] <- calculate_prize(w) } # Check with known answers subset(slots, prize != prize_c) # Uh oh! What is the problem? Think about the most generalise case Monday, 21 September 2009
  • 28. DD DD DD 800 windows <- c("DD", "C", "C") 7 7 7 80 # How can we calculate the BBB BBB BBB 40 # payoff? B B B 10 C C C 10 Any bar Any bar Any bar 5 C C * 5 C * C 5 C * * 2 * C * 2 DD doubles any winning combination. Two DD * * C 2 quadruples. DD is wild Monday, 21 September 2009