0

I am trying to use a function to update a variable inside a data frame. In order to illustrate it, I've made an easy example of what is going on. I need to update a value and the function I created works well, I mean it makes all the calculations but it does not update it. This is what happens:

a <- 1
plus_points <- function(points) {
        a <- a + points
        return(a)
} 
plus_points(2)
a

The sentence plus_points(2) yields 3, it's ok this is the outcome I expected, but if I run the object a the outcome is 1 again, I was expecting a satisfactory 3. Never happened. Thanks for your advice.

iván mendivelso
  • 63
  • 1
  • 1
  • 8
  • 1
    Functions in R try not to modify variables outside of their private scopes. Things work best if functions don't have side effects like modifying global variables. It's better for functions to return values that you can assign somewhere if you like. It is technically possible to make this work with `<<-` but it is very un-R-like and if you are new to R I would strong suggest avoiding this at least while you are getting started. – MrFlick Aug 02 '20 at 23:20
  • Very grateful for your advice. I will stick to it and look for another way to get the result I need. – iván mendivelso Aug 03 '20 at 00:24

0 Answers0