[R] Trouble variable scoping a function writing with get()

Bert Gunter gunter.berton at gene.com
Wed Jan 26 23:35:07 CET 2011


It's looking for an object named "b" in the frame of the function.
There is none. You need to specify

get(response, pos = parent.frame())

## or maybe even

get(response, pos= globalenv())

HOWEVER, this is **exactly** why you shouldn't do this! Instead of
passing in the name of the object, pass in the object itself (response
= b, not response = "b") and forget about using get(). Then it
**would** work as writted without getting tangled up in scoping. The
whole point local (to the function) scope and call by value is to
avoid exactly the sort of mess that you've gotten yourself into. Stick
with R's programming paradigms in R rather than trying to impose
others and life will be simpler and sweeter.

-- Bert



On Wed, Jan 26, 2011 at 2:21 PM, Pat Schmitz <pschmitz at illinois.edu> wrote:
> I am having trouble with variable scoping inside/outside functions.  I
> want to use get() to grab a named and quoted variable as an input to a
> function, however the function can't find the variable when it is entered
> into the function call, only when it is named in the main environment.
>
> I obviously am not so clear on variable scoping, and ?get really doesn't
> clear up my confusion.
>
> I am sure that there are better, more appropriate ways to write a
> function...
>
> Please enlighten me,
> Pat
>
> # Example code
>
> dat <- expand.grid(a = factor(c("a", "b")), b=1:10)
>
> # Function that requires get()
> ex <- function(data, response){
>  library(plyr)
>  output <- ddply(data,
> .(a),
> summarize,
>  res = sum(get(response))
> )
> return(output)
> }
>
>
> out <- ex(data = dat, response = "b")
> # Error in get(response) : object 'response' not found
>
> # However if I name reponse outside of the function, it is found by the
> function
> response = "b"
> out <- ex(data = dat, response = "b")
> out
> #> out
> #  a res
> #1 a  55
> #2 b  55
>
>
> --
> Patrick Schmitz
> Graduate Student
> Plant Biology
> 1206 West Gregory Drive
> RM 1500
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Bert Gunter
Genentech Nonclinical Biostatistics



More information about the R-help mailing list