0

I have a function

Trace.repair(dat, row.names)

While performing this function i change values in my table dat. Is there a way to update dat without doing the obvious

dat<-Trace.repair(dat, row.names){blah; blah; print(dat)}
MadmanLee
  • 478
  • 1
  • 5
  • 18
  • 2
    See http://stackoverflow.com/questions/2603184/r-pass-by-reference – jwdink Jan 07 '16 at 04:17
  • Can you make your a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Heroka Jan 07 '16 at 06:56

1 Answers1

1

use assign. Something like this:

Trace.repair <- function(x) {
     # do tricks with x
  assign("dat", x, envir=parent.frame())
}

This assumes that you always want to change variable "dat" in your calling environment. If you want the outcome to be assigned to the variable with the same name as you call it, like Trace.repair(another_dat), you can recover the variable name by as.character(sys.call()[2]) and replace "dat" in the code with that:

Trace.repair <- function(x) {
     # do tricks with x
   assign(as.character(sys.call()[2]), x, envir=parent.frame())
}

However, if you don't call it with explicit variable name but with something like Trace.repair(-dat), then you get a variable named "-dat" in your environment.

Ott Toomet
  • 1,894
  • 15
  • 25
  • my dat is also a list. So i am actually working with dat$bin – MadmanLee Jan 07 '16 at 04:25
  • Can you give an example what do you want to achieve? – Ott Toomet Jan 07 '16 at 04:36
  • Could you tell me what is going on with 'sys.call' , and 'parent.frame'? When i call sys.call()[2], on the command line, all i get is NULL. But it works well for my functions where the only input is a dataframe, and not a dataframe from a list of dataframes. – MadmanLee Jan 11 '16 at 16:50
  • `sys.call()` gives the list of arguments about how the function was called. The first one is the function name, the next one the first argument, and so on. If you call it just in command line, it is not inside of any function and I don't know what it does then. `envir` tells which environment you want to use. `parent.frame` is where the function was called from, `.GlobalEnv` is the common workspace. If you want your variable to sit in the workspace, then you probably can ignore that argument. But just try, use `browser()` command inside of your function and test :-) – Ott Toomet Jan 11 '16 at 19:26