Saving a table and functions in runtime environment

Hi, I cannot save a deck of cards and related functions from global environment into runtime environment. I downloaded the deck of cards from the website https://gist.github.com/garrettgman/9629323

Code for saving the deck into runtime environment

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())
}
}
setup
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)
}
deal <- cards$deal
shuffle <- cards$shuffle

When I check for the environment where deal is saved I get still the global environment.

environment (deal)

Could you please help me?
Thank you and best, Svita

I think you will need to get the deck from the global environment when you want to use it inside a function. It's safer than relying on the function to look in its parent envir.

setup <-function(initial_deck) {
  assign("deck", initial_deck, envir = globalenv()) # create deck with initial_deck
}
DEAL <- function () {
  deck <- get("deck", envir = globalenv())
  card <- deck[1,]
  assign ("deck", deck[-1,], envir =globalenv())
  card
}
SHUFFLE <- function () {
  deck <- get("deck", envir = globalenv())
  ncards <- nrow(deck)
  if (ncards > 0){
    random <- sample (1:ncards, size = ncards)
    assign ("deck", deck[random, ], envir =globalenv())
    deck[random, ]
  } else {
    NULL
  }
}

initial_deck <- data.frame(number = rep(1:13, 4), suit = rep(1:4, 13))
setup(initial_deck) # what deck are you sending to setup()?
deal <- DEAL() 
shuffle <- SHUFFLE()

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

Thank you very much. I found the mistake in my code. I ought to add cards <- setup (deck) after the defining of three functions.