Re: [R] (Newbie)Basic Basic global vs. local variables

From: jim holtman <jholtman_at_gmail.com>
Date: Mon 02 Apr 2007 - 02:03:17 GMT

The following will work, but I would suggest that you redesign your functions so that they do not use 'globals'; It is not nice for functions to have side-effects.

g_Means<-numeric()

defineSamples<- function()

       {
               g_Means <<-5      # check out ?"<<-"
       }

runit<-function()
       {
               defineSamples()
               g_Means #####<<This returns "numeric(0)", and not "5"
       }

runit()

A better way might be: no side effects

defineSamples<- function()

       {
              5

       }

runit<-function()
       {
               defineSamples()

       }

runit()

On 4/1/07, projection83 <mkurowski@gmail.com> wrote:
>
>
> My R code has got too complex to have a non-modular approach. Ive done
> some
> coding in other languages before, but I somehow cant figure out R's
> general
> rules for global and local variables. I have put a simple code below, if
> anyone can show me what i need to add to make this work, i would greatly
> appreciate it!
>
> #----------------------------------------
> g_Means<-numeric()
>
> defineSamples<- function()
> {
> g_Means<-5
> }
>
> runit<-function()
> {
> defineSamples()
> g_Means #####<<This returns "numeric(0)", and not "5"
> }
>
> runit()
> #----------------------------
> Basically I can not get the parameter I set from a global scale...
> --
> View this message in context:
> http://www.nabble.com/%28Newbie%29Basic-Basic-global-vs.-local-variables-tf3503101.html#a9783571
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

	[[alternative HTML version deleted]]

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Mon Apr 02 12:11:00 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 02 Apr 2007 - 20:32:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.