Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify variable within R function

How do I modify an argument being passed to a function in R? In C++ this would be pass by reference.

g=4
abc <- function(x) {x<-5}
abc(g)

I would like g to be set to 5.

like image 335
Alex Avatar asked Dec 07 '11 17:12

Alex


People also ask

How do you modify a variable in R?

The mutate() function is used to modify a variable or recreate a new variable. Variable are changed by using the name of variable as a parameter and the parameter value is set to the new variable.

Which R function can be used to make changes to a data frame?

transform() function in R Language is used to modify data. It converts the first argument to the data frame. This function is used to transform/modify the data frame in a quick and easy way.

Can we modify global variable?

Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).


2 Answers

There are ways as @Dason showed, but really - you shouldn't!

The whole paradigm of R is to "pass by value". @Rory just posted the normal way to handle it - just return the modified value...

Environments are typically the only objects that can be passed by reference in R.

But lately new objects called reference classes have been added to R (they use environments). They can modify their values (but in a controlled way). You might want to look into using them if you really feel the need...

like image 110
Tommy Avatar answered Oct 12 '22 02:10

Tommy


There has got to be a better way to do this but...

abc <- function(x){eval(parse(text = paste(substitute(x), "<<- 5")))}
g <- 4
abc(g)
g

gives the output

[1] 5
like image 25
Dason Avatar answered Oct 12 '22 04:10

Dason