1

Possible Duplicate:
Global variables in R

ad the beginning of the file I wrote:

t.code = c()

then in a function like:

calc <- function(){

   ..some stuff

   t.code = append(t.code, value)
}

at the end i print the t.code content but I see NULL, so it seems that the global var is not used, any advice?

Community
  • 1
  • 1
Dail
  • 4,622
  • 16
  • 74
  • 109
  • 3
    The idiomatic way to assign a variable in R is to use `<-` rather than `=`. But you are looking for `<<-` in this case: http://stat.ethz.ch/R-manual/R-devel/library/base/html/assignOps.html From the docs: The operators <<- and ->> cause a search to made through the environment for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment. – David Heffernan Mar 21 '12 at 19:43
  • 1
    Assigning to a global variable is very rarely necessary (or a good idea) especially if you're new to R. I would instead have your function `return(value)` and append in a separate step. – Justin Mar 21 '12 at 19:49

1 Answers1

4

You can but you'll have to use the global assignment operator <<- (or somewhat more sophisticated, assign).

t.code <<- append(t.code,value)

And now the standard disclaimer: the use of <<- is often discouraged, as that style of programming is not really the sort of idiom that R was intended for.

You might benefit from a careful reading of R's scoping rules.

joran
  • 169,992
  • 32
  • 429
  • 468