0

I come from OOP background (C#/Java to be specific) and I really do not understand how R treat the variable from outside the function.

I made this example:

result = list();
result$total = 0;
result$count = 0;

result$something = "abc";

a = 1:10;
b = 10:20;

mapply(function(x, y) {
    print(result$something);

    # Does not work with either = or <--
    result$total <-- result$total + x + y;
    result$count <-- result$count + 1;

    print(result$count);
}, x = a, y = b);

result$average = result$total / result$count;
print(result$total);
print(result$count);
print(result$average);

Here, clearly result is available to the anonymous function because the program did print "abc" 10 times.

However, the change to its component total and count does not survive. 10 times it prints 1 for the result$count, and the final 3 lines are 0, 0 and NaN.

Why is this happening? What should I do in this case, if I want the function to be able to change the variable value?

Note: in my real case, result is NOT a global variable, but is inside another function, and I will use return (result) from the function.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • 2
    Did you mean to use `<<-` and not `<--`? The later is normal assignment followed by numerical unary negation – James Dec 21 '17 at 11:20
  • Within the function you can use `<<-` to change/ create the variable in the parent environment. But this would not change it within the function itself! So if you stil want to print `count`then you need `result$count <<- result$count + 1` and `result$count <- result$count + 1`. For a better understanding of the usage of environments and what is called when you could read this: http://adv-r.had.co.nz/Environments.html – Jakob Gepp Dec 21 '17 at 11:35
  • 1
    I'll add the obligatory comment that R is not meant to be used this way (functions modifying external objects). If you need to modify an object in a function, you should generally pass that object as an argument, modify it and then return and reassign it. Don't delve into things like `<<-` and `assign` while you're still learning R, they will become a crutch that cause you to write code in patterns from other languages rather than learning R. – joran Dec 21 '17 at 15:52
  • Thank you, I was my mistake using `<--` instead of `<<-`. `<<-` works correctly, but as @joran mentioned, what should I do instead? How can I pass a single variable into `mapply` anonymous function? – Luke Vo Dec 22 '17 at 02:14
  • mapply isn’t what you want here. Just write a for loop if you can’t vectorize it. – joran Dec 22 '17 at 03:07

0 Answers0