1

Consider the following R-code:

i <- 10
j <- 0
m <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2, byrow = TRUE)
apply(m, 1, function(x) {
 if(i > 0)
  j<-1 
  else 
   j<-2 
 return <- i
})

Inside the function we can read the content of the variable i, but we cannot manipulate the content of the variable j? But when we can read variables inside the function I would expect that we can assign new values to them too? So can someone explain what is happening here?

StefanH
  • 131
  • 4
  • 1
    It's generally bad form in R to implicitly alter the values of global variables from within a function. The preferred method is to do this explicitly by assigning the new value of the output of the function. Within the function, you are altering a copy of i rather than i itself. – lmo Jan 21 '17 at 16:28
  • 2
    Possible duplicate of [Update data frame via function doesn't work](http://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work) – user2100721 Jan 21 '17 at 16:29
  • 1
    To assign in global environment you can use `<<-` or `assign` – Raad Jan 21 '17 at 16:33
  • @NBATrends You *can*, but it's almost never a good idea "[because global variables introduce non-obvious dependencies between functions](http://adv-r.had.co.nz/Environments.html)" – Phil Jan 21 '17 at 20:51
  • 1
    @phil I agree here, never implied it was a good idea. Just showing how it can be done – Raad Jan 21 '17 at 20:53

0 Answers0