[R] Changing global variables from functions

David Winsemius dwinsemius at comcast.net
Tue Mar 16 19:02:34 CET 2010


On Mar 16, 2010, at 11:04 AM, jtouyz wrote:

>
> Hey all,
> I'm relatively new to the R-environment. I'm having a bit of trouble  
> with
> encapsulation.
> I have a globally declared variable that doesn't update it when I  
> change it
> in a function.

> For example when I run the following function
>
>> deckn<-NULL
>> deck1<-1  #52 card deck
>> deck<-function()
> {
> #Creating a standard deck
> deck1<-c(1:52)
> deckn<-deck1
>    #Creating n decks
>    for (i in 2:num_decks)

# could be wrong but it appears that you are expecting the act of  
putting "num_" in front of "decks" to be interpreted by R as returning  
the length of deckn or deck1. That is a higher level of abstraction  
than is yet available in any computer language with which I am  
familiar. Or perhaps you were intending to use Greg Snow's soon to be  
released mind-reading package so that R could know that you wanted it  
to be 6?.

Perhaps instead (depending on what the real problem (unstated as yet)  
might be:

   for (i in 2:length(deck1) )  # or some other object or function  
that returns a numeric value.

>    {
>    deckn<-c(deckn,52*i+deck1-1)

>    }
> }
>> deckn

You would have needed to assign a "return"-ed value to deckn in the  
outer environment. The deckn object would have disappeared at the end  
of the function call, and it would not have needed to be named  
"deckn", either.


Try instead:

deckn<-NULL
deck<-function(num_decks=6)
{
#Creating a standard deck
deck1<-c(1:52)
deckn<-deck1
    #Creating n decks
    for (i in 2:num_decks)
    {
    deckn<-c(deckn,52*i+deck1-1)
    }; return(deckn)
}
deckn <- deck()
deckn

Which has a gap between 52 and 104 because of your logic, not mine.


>> NULL
>
> it returns NULL for deckn instead of a vector of values. Is there an  
> easy
> fix to update deckn in the function so that it outputs a vector of  
> values (
> I don't wish the function to return a value just update the current  
> one)?

You could, of course, explain what you are trying to do.

>
> Thanks in advance,
> Josh Elliott
> -- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list