Re: [R] function that uses a variable name as the parameter

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Wed, 12 Nov 2008 08:30:59 -0500

On 12/11/2008 7:59 AM, David Croll wrote:
>
> Hello dear R people!
>
>
> Several times it occurred to me that a function that uses a variable name as a parameter would be helpful, but I did not find out how to write such a function. I have experience in several programming language, but I did not come across a helpful trick...
>
> What I want to have is...
>
> a <- 12 # starting value
>
> add <- function(variable,increment) {
>
> variable <- variable + increment
>
> }
>
> # by typing a and 25 for example, you specify that 25 will be added to the variable a...
>
> add(a,25)
>
> # the new a equals 12 + 25 = 37
>
> Thanks for all the help – I'll try to give my advice when I get across a problem I can solve!

That's not a good idea: it looks as though you're trying to fake "call by reference" in a call by value language. R is flexible enough to do it (use substitute() to change the arg into a string, get() to get the old value, assign() to put it back), but the behaviour will be really weird, and you'll probably run into problems later. R is not C.

Duncan Murdoch



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Wed 12 Nov 2008 - 13:42:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 12 Nov 2008 - 14:00:24 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive