[R] Trying to learn how to write a function... can't define a variable??

David Winsemius dwinsemius at comcast.net
Fri Sep 7 22:37:40 CEST 2012


On Sep 7, 2012, at 1:34 PM, David Winsemius wrote:

> 
> On Sep 7, 2012, at 11:00 AM, wwreith wrote:
> 
>> I am just starting to experiment with writing a function and have run into
>> what seems like a limitation or more likely a lack of understanding on my
>> part. 
>> 
>> Very Simple Example:  I want to define a function that does 1+1=2.
>> 
>> z<-1
>> ADD<-function(x)
>> {
>> x<-x+1
>> }
>> ADD(z)
>> z
>> output for z is 1 not the expected 2. 
>> 
>> Now if I were to do print(x+1) instead of x<-x+1 it does return 2, so the
>> function seems ok with x+1, but not ok with x<-. Is there a way to define a
>> variable inside a function or am I violating some rule that I don't know
>> about?
> 
> The rule you are violating is failing to assign the calculated value in the proper environment. The x=1 value

I meant to write "x+1" ^^^   (aka: failure to shift)

> exists inside the function and _is_ returned, but you didn't do anything with it, so it has no name and will get garbage collected. Here's an incrementer function that works:
> 
> ADD <- function(x) assign( deparse(substitute(x)), x+1, envir=parent.frame() )
> x=1
> ADD(x)
> x
> #[1] 2
> 
> You could also have written it thusly:
> 
> ADD <- function(x) x <<- x+1 )
> 
> (But that operator is frowned upon by those in the know.)
> 
> I'm not sure what sort of reaction would be provoked by:
> 
> ADD <- function(x) {  eval.parent(substitute(x <- x + 1)) }
> 
> The data.table package does in-memory alterations in its objects using a database model. It is often much faster than reassignment of dataframes to them self or even adding a columns, which does require making a copy (or maybe even two) of the entire object.
> 
> -- 
> David Winsemius, MD

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list