Skip to content

Code works, but not as function.

2 messages · Benjamin Ward (ENV), Peter Langfelder

#
On Thu, Nov 15, 2012 at 5:48 PM, Benjamin Ward (ENV) <B.Ward at uea.ac.uk> wrote:
The problem is that R functions do not operate on objects in the
global environment, where your list lives. They make a copy and
operate on that copy; when the function exists, that local copy is
discarded.

Here's a very simple example:

# Function to change a
change.a.wrong = function(new.a)
{
  a = new.a;
  print(paste("Changed value of a to", a))
}

#Initialize a to 1
a = 1

# change it to 5
change.a.wrong(5)

# but a is still 1!
a
[1] 1

The local copy of a is changed to 5, but discarded and the global copy
whose value is still 1 lives on.

The solution is to return the value of the variable you have changed,
and assign it to the original name. In your case you would define a
function

Eff.Mutate = function(x)
{
  ...your code changes x
  return(x)
}

and you would call it as

effectors.new = Eff.Mutate(effectors)

or so.

HTH,

Peter