SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
Stat405                Problem solving


                                Hadley Wickham
Wednesday, 16 September 2009
Homework
                   Great improvement. A few tips:
                   Headings should be in sentence case, and be a
                   single sentence summary of the section.
                   Include ggsave calls in your code.
                   Don’t use " and " to get “ and ”.
                   Use ` ` and ' '.
                   (Also, I think I’ve been grading quite hard. Think
                   of a 5 as an A+, a 4 as an A, and a 3 as an A-/B+)


Wednesday, 16 September 2009
Feedback
                   Speed seems about right.
                   Frustration is a natural part of the learning
                   experience. You will get better! In
                   particularly, it will get easier to find
                   interesting plots (helps to start homework
                   early!)
                   Split homework help session? Also, feel
                   free to email me to set up time to talk.


Wednesday, 16 September 2009
1. Recap of problem
               2. Task
               3. Basic strategy
               4. Turning ideas into code




Wednesday, 16 September 2009
Slots
                   Casino claims that slot machines have
                   prize payout of 92%. Is this claim true?
                   mean(slots$payoff)
                   t.test(slots$prize, mu = 0.92)
                   qplot(prize, data = slots, binwidth = 1)
                   Can we do better?


Wednesday, 16 September 2009
Bootstrapping
                   Slot machine is basically a random
                   number generator - three numbers
                   between 1 and 7. We can generate a new
                   number by sampling from the data.
                   Doing that lots of times, and calculating
                   the payoff should give us a better idea of
                   the payoff. But first we need some way to
                   calculate the prize from the windows


Wednesday, 16 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.
Wednesday, 16 September 2009
Your turn


                   There are three basic cases of prizes.
                   What are they? Take 3 minutes to
                   brainstorm with a partner.




Wednesday, 16 September 2009
Cases

                   1. All windows have same value
                   2. A bar (B, BB, or BBB) in every window
                   3. Cherries and diamonds




Wednesday, 16 September 2009
Same values




Wednesday, 16 September 2009
Same values

                   1. Determine that all windows are the
                      same. How?




Wednesday, 16 September 2009
Same values

                   1. Determine that all windows are the
                      same. How?
                   2. Given single window, look up prize
                      value. How?




Wednesday, 16 September 2009
Same values

                   1. Determine that all windows are the
                      same. How?
                   2. Given single window, look up prize
                      value. How?

                                    With a partner, brainstorm
                                    for 2 minutes on how to
                                    solve one of these problems
Wednesday, 16 September 2009
# Same value
         same <- length(unique(windows)) == 1

         # OR
         same <- windows[1] == windows[2] &&
                 windows[2] == windows[3]

         if (same) {
           # Lookup value
         }



Wednesday, 16 September 2009
If
                   if (cond) expression
                   Cond should be a logical vector of length 1
                   Use && and || to combine sub-conditions
                               Not & and | - these work on vectors
                               && and || are “short-circuiting”: they
                               do the minimum amount of work


Wednesday, 16 September 2009
if (TRUE) {
       # This will be run
     }

     if (FALSE) {
       # This won't be run
     } else {
       # This will be
     }

     # Single line form: (not recommended)
     if (TRUE) print("True!)
     if (FALSE) print("True!)


Wednesday, 16 September 2009
if (TRUE) {
       # This will be run
     }

     if (FALSE) {
       # This won't be run
     } else {
       # This will be
     }
         Note indenting.
         Very important!
     # Single line form: (not recommended)
     if (TRUE) print("True!)
     if (FALSE) print("True!)


Wednesday, 16 September 2009
x <- 5
     if (x < 5) print("x < 5")
     if (x == 5) print("x == 5")

     x <- 1:5
     if (x < 3) print("What should happen here?")

     if (x[1] < x[2]) print("x1 < x2")
     if (x[1] < x[2] && x[2] < x[3]) print("Asc")
     if (x[1] < x[2] || x[2] < x[3]) print("Asc")




Wednesday, 16 September 2009
if (window[1] == "DD") {
       prize <- 800
     } else if (windows[1] == "7") {
       prize <- 80
     } else if (windows[1] == "BBB") ...

     # Or use                  subsetting
     c("DD" =                  800, "7" =   80,   "BBB"   =   40)
     c("DD" =                  800, "7" =   80,   "BBB"   =   40)["BBB"]
     c("DD" =                  800, "7" =   80,   "BBB"   =   40)["0"]
     c("DD" =                  800, "7" =   80,   "BBB"   =   40)[window[1]]



Wednesday, 16 September 2009
Your turn


                   Complete the previous code so that if all
                   the values in win are the same, then prize
                   variable will be set to the correct amount.




Wednesday, 16 September 2009
All bars

                   How can we determine if all of the
                   windows are B, BB, or BBB?
                   (windows[1] == "B" ||
                    windows[1] == "BB" ||
                    windows[1] === "BBB") && ... ?




Wednesday, 16 September 2009
All bars

                   How can we determine if all of the
                   windows are B, BB, or BBB?
                   (windows[1] == "B" ||
                    windows[1] == "BB" ||
                    windows[1] === "BBB") && ... ?

                                   Take 2 minutes to brainstorm
                                   possible solutions
Wednesday, 16 September 2009
windows[1] %in% c("B", "BB", "BBB")
     windows %in% c("B", "BB", "BBB")

     allbars <- windows %in% c("B", "BB", "BBB")
     allbars[1] & allbars[2] & allbars[3]
     all(allbars)


     # See also ?any for the complement




Wednesday, 16 September 2009
Your turn

                   Complete the previous code so that the
                   correct value of prize is set if all the
                   windows are the same, or they are all
                   bars




Wednesday, 16 September 2009
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
     }



Wednesday, 16 September 2009
Cherries

                   Need numbers of cherries, and numbers
                   of diamonds (hint: use sum)
                   Then need to look up values (like for the
                   first case) and multiply together




Wednesday, 16 September 2009
cherries <- sum(windows == "C")
         diamonds <- sum(windows == "DD")

         c(0, 2, 5)[cherries + 1] *
           c(1, 2, 4)[diamonds + 1]




Wednesday, 16 September 2009
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]
     }

Wednesday, 16 September 2009
Writing a function

                   Now we need to wrap up this code in to a
                   reusable fashion. We need a function
                   Have used functions a lot, and this will be
                   our first time writing one




Wednesday, 16 September 2009
Basic structure
                   • Name
                   • Input arguments
                        • Names/positions
                        • Defaults
                   • Body
                   • Output value


Wednesday, 16 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
     }

Wednesday, 16 September 2009
Homework

                   What did we miss? Find out the problem
                   with our scoring function and fix it.
                   Also, some readings related to group
                   work.




Wednesday, 16 September 2009

Weitere ähnliche Inhalte

Ähnlich wie 07 Problem Solving

Latinoware Rails 2009
Latinoware Rails 2009Latinoware Rails 2009
Latinoware Rails 2009Fabio Akita
 
Semcomp de São Carlos
Semcomp de São CarlosSemcomp de São Carlos
Semcomp de São CarlosFabio Akita
 
Strategies and Tools for Parallel Machine Learning in Python
Strategies and Tools for Parallel Machine Learning in PythonStrategies and Tools for Parallel Machine Learning in Python
Strategies and Tools for Parallel Machine Learning in PythonOlivier Grisel
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMatt Aimonetti
 

Ähnlich wie 07 Problem Solving (10)

08 functions
08 functions08 functions
08 functions
 
09 Simulation
09 Simulation09 Simulation
09 Simulation
 
24 Spam
24 Spam24 Spam
24 Spam
 
14 Ddply
14 Ddply14 Ddply
14 Ddply
 
Latinoware Rails 2009
Latinoware Rails 2009Latinoware Rails 2009
Latinoware Rails 2009
 
21 Polishing
21 Polishing21 Polishing
21 Polishing
 
Playing With Ruby
Playing With RubyPlaying With Ruby
Playing With Ruby
 
Semcomp de São Carlos
Semcomp de São CarlosSemcomp de São Carlos
Semcomp de São Carlos
 
Strategies and Tools for Parallel Machine Learning in Python
Strategies and Tools for Parallel Machine Learning in PythonStrategies and Tools for Parallel Machine Learning in Python
Strategies and Tools for Parallel Machine Learning in Python
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meet
 

Mehr von 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
 
19 tables
19 tables19 tables
19 tables
 
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
 
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
 

Kürzlich hochgeladen

Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...Nguyen Thanh Tu Collection
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 

Kürzlich hochgeladen (20)

Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 8 - CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC ...
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 

07 Problem Solving

  • 1. Stat405 Problem solving Hadley Wickham Wednesday, 16 September 2009
  • 2. Homework Great improvement. A few tips: Headings should be in sentence case, and be a single sentence summary of the section. Include ggsave calls in your code. Don’t use " and " to get “ and ”. Use ` ` and ' '. (Also, I think I’ve been grading quite hard. Think of a 5 as an A+, a 4 as an A, and a 3 as an A-/B+) Wednesday, 16 September 2009
  • 3. Feedback Speed seems about right. Frustration is a natural part of the learning experience. You will get better! In particularly, it will get easier to find interesting plots (helps to start homework early!) Split homework help session? Also, feel free to email me to set up time to talk. Wednesday, 16 September 2009
  • 4. 1. Recap of problem 2. Task 3. Basic strategy 4. Turning ideas into code Wednesday, 16 September 2009
  • 5. Slots Casino claims that slot machines have prize payout of 92%. Is this claim true? mean(slots$payoff) t.test(slots$prize, mu = 0.92) qplot(prize, data = slots, binwidth = 1) Can we do better? Wednesday, 16 September 2009
  • 6. Bootstrapping Slot machine is basically a random number generator - three numbers between 1 and 7. We can generate a new number by sampling from the data. Doing that lots of times, and calculating the payoff should give us a better idea of the payoff. But first we need some way to calculate the prize from the windows Wednesday, 16 September 2009
  • 7. 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. Wednesday, 16 September 2009
  • 8. Your turn There are three basic cases of prizes. What are they? Take 3 minutes to brainstorm with a partner. Wednesday, 16 September 2009
  • 9. Cases 1. All windows have same value 2. A bar (B, BB, or BBB) in every window 3. Cherries and diamonds Wednesday, 16 September 2009
  • 10. Same values Wednesday, 16 September 2009
  • 11. Same values 1. Determine that all windows are the same. How? Wednesday, 16 September 2009
  • 12. Same values 1. Determine that all windows are the same. How? 2. Given single window, look up prize value. How? Wednesday, 16 September 2009
  • 13. Same values 1. Determine that all windows are the same. How? 2. Given single window, look up prize value. How? With a partner, brainstorm for 2 minutes on how to solve one of these problems Wednesday, 16 September 2009
  • 14. # Same value same <- length(unique(windows)) == 1 # OR same <- windows[1] == windows[2] && windows[2] == windows[3] if (same) { # Lookup value } Wednesday, 16 September 2009
  • 15. If if (cond) expression Cond should be a logical vector of length 1 Use && and || to combine sub-conditions Not & and | - these work on vectors && and || are “short-circuiting”: they do the minimum amount of work Wednesday, 16 September 2009
  • 16. if (TRUE) { # This will be run } if (FALSE) { # This won't be run } else { # This will be } # Single line form: (not recommended) if (TRUE) print("True!) if (FALSE) print("True!) Wednesday, 16 September 2009
  • 17. if (TRUE) { # This will be run } if (FALSE) { # This won't be run } else { # This will be } Note indenting. Very important! # Single line form: (not recommended) if (TRUE) print("True!) if (FALSE) print("True!) Wednesday, 16 September 2009
  • 18. x <- 5 if (x < 5) print("x < 5") if (x == 5) print("x == 5") x <- 1:5 if (x < 3) print("What should happen here?") if (x[1] < x[2]) print("x1 < x2") if (x[1] < x[2] && x[2] < x[3]) print("Asc") if (x[1] < x[2] || x[2] < x[3]) print("Asc") Wednesday, 16 September 2009
  • 19. if (window[1] == "DD") { prize <- 800 } else if (windows[1] == "7") { prize <- 80 } else if (windows[1] == "BBB") ... # Or use subsetting c("DD" = 800, "7" = 80, "BBB" = 40) c("DD" = 800, "7" = 80, "BBB" = 40)["BBB"] c("DD" = 800, "7" = 80, "BBB" = 40)["0"] c("DD" = 800, "7" = 80, "BBB" = 40)[window[1]] Wednesday, 16 September 2009
  • 20. Your turn Complete the previous code so that if all the values in win are the same, then prize variable will be set to the correct amount. Wednesday, 16 September 2009
  • 21. All bars How can we determine if all of the windows are B, BB, or BBB? (windows[1] == "B" || windows[1] == "BB" || windows[1] === "BBB") && ... ? Wednesday, 16 September 2009
  • 22. All bars How can we determine if all of the windows are B, BB, or BBB? (windows[1] == "B" || windows[1] == "BB" || windows[1] === "BBB") && ... ? Take 2 minutes to brainstorm possible solutions Wednesday, 16 September 2009
  • 23. windows[1] %in% c("B", "BB", "BBB") windows %in% c("B", "BB", "BBB") allbars <- windows %in% c("B", "BB", "BBB") allbars[1] & allbars[2] & allbars[3] all(allbars) # See also ?any for the complement Wednesday, 16 September 2009
  • 24. Your turn Complete the previous code so that the correct value of prize is set if all the windows are the same, or they are all bars Wednesday, 16 September 2009
  • 25. 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 } Wednesday, 16 September 2009
  • 26. Cherries Need numbers of cherries, and numbers of diamonds (hint: use sum) Then need to look up values (like for the first case) and multiply together Wednesday, 16 September 2009
  • 27. cherries <- sum(windows == "C") diamonds <- sum(windows == "DD") c(0, 2, 5)[cherries + 1] * c(1, 2, 4)[diamonds + 1] Wednesday, 16 September 2009
  • 28. 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] } Wednesday, 16 September 2009
  • 29. Writing a function Now we need to wrap up this code in to a reusable fashion. We need a function Have used functions a lot, and this will be our first time writing one Wednesday, 16 September 2009
  • 30. Basic structure • Name • Input arguments • Names/positions • Defaults • Body • Output value Wednesday, 16 September 2009
  • 31. 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 } Wednesday, 16 September 2009
  • 32. Homework What did we miss? Find out the problem with our scoring function and fix it. Also, some readings related to group work. Wednesday, 16 September 2009