Nathan Nathan - 1 year ago 61
R Question

In R, is it possible to create a new object inside a function and pass it to the parent enviroment?

The function would look something like:

function(input, FUN, output) {

output <- FUN(input)



Where output is an unquoted name of an object to be created.

Let's skip the part where this is probably a bad idea: is this sort of thing possible? How would you go about doing it?

Answer Source

Clean code would just return it.

But you have other options:

  • the <<- operator
  • the assign() function where you can list the environment to assign to

Here is a trivial example:

R> foo <- function(x=21) { y <<- 2*x; return(3*x) }
R> foo(10)
[1] 30
R> y
[1] 20
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download