0

I am unable to replicate an example from the book "Hands-on Programming with R". I have literally cut / copied the code from the book, but it simply won't work.

setup <- function(deck) {
  DECK <- deck
  DEAL <- function() {
  card <- deck[1, ]
  assign("deck", deck[-1, ], envir = globalenv())
  card
}

SHUFFLE <- function(){
  random <- sample(1:52, size = 52)
  assign("deck", DECK[random, ], envir = globalenv())
}

list(deal = DEAL, shuffle = SHUFFLE)
}

cards   <- setup(deck)
deal    <- cards$deal
shuffle <- cards$shuffle

The objective is to use the returned list to make two functions: one that shuffles a card deck, and another to deal a card and then remove the card once dealt.

When I cut / copy the individual functions they work:

DEAL <- function() {
  card <- deck[1, ]
  assign("deck", deck[-1, ], envir = globalenv())
  card
}

SHUFFLE <- function(){
  random <- sample(1:52, size = 52)
  assign("deck", DECK[random, ], envir = globalenv())
}

But when I attempt to assign the functions using the returned list by the setup() the code no longer works. Sigh.

Any help would be appreciated.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • 2
    What does "won't work" mean? What is the error message? – neilfws Dec 15 '20 at 23:23
  • 1
    You should read this: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 in order to write a question that will make it easier for people to help you. And you should take your additional information from your "answer" and add that to your question by editing your question. And delete that answer. – John Polo Dec 15 '20 at 23:39
  • What section of hands on programming does this come from? This code just doesn't look correct. – MrFlick Dec 16 '20 at 00:01
  • Thank you, @johnpolo I am new to Stackoverflow. – Shane_Urban Dec 16 '20 at 03:42
  • @MrFlick At the end of chapter six when he discusses Closures. – Shane_Urban Dec 16 '20 at 03:53
  • I don't think you're using the right code chunk. The working code I see in the online version uses `assign("deck", deck[-1, ], envir = parent.env(environment()))` from chapter 8 here https://rstudio-education.github.io/hopr/environments.html. The dicussion of why that change needs to be made is shortly after Figure 8.8. – MrFlick Dec 16 '20 at 04:01

0 Answers0