PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

[FIXED] How to use the R environment and the globalenv() function

 August 22, 2022     environment, environment-variables, r, scoping, storage     No comments   

Issue

I'm currently reading Hands-On Programming With R and the author first suggests this code to deal cards from the top of a deck:

deal <- function(deck) {
deck[1,]}

but that code has an obvious problem: you'll always get the same card, since the function does not remove the card from the deck after it has been dealt.

As a solution, he suggests this code:

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

I feel like I don't properly understand what's going on with the envir = globalenv() part. I do know that it has something to do with removing the card that has been dealt from the deck, but can someone please elucidate what is happening there exactly?


Solution

Your card deck is stored in a vector deck in your Global Environment.

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

Each function call creates it's own environment, an object assigned inside a function "lives" just inside of it. That's why you don't "see" a vector named card in your Global Environment (unless you created one before, but this vector is uneffected by deal functions card <- deck[1,] statement).

So assign("deck", deck[-1]) (without the envir argument) would be the same as

deal <- function(){
  card <- deck[1,]
  deck <- deck[-1,]
  card
}

but this won't change your deck outside the function. The vector deck inside the function just exists inside the function. To change the deck outside the function, you have to tell R where to change it. So that's why assign("deck", deck[-1,], envir = globalenv()) is used.

So let's start over with your function deal:

card <- deck[1,]

assigns the first element of deck to card. But wait! deck doesn't exists inside the function? So how is this possible? If the object isn't found inside the function, R looks one level up, in your case most likely the Global Environment. So there R finds an object/vector named deck and does the assignment. Now we have an object/vector named card that exists inside the function.

For further understanding, take a look at Chapter 6: Functions in Advanced R.



Answered By - Martin Gal
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing