[R] puzzles with assign()

Duncan Murdoch murdoch.duncan at gmail.com
Wed May 5 13:36:50 CEST 2010


David.Epstein wrote:
> I'm trying to get code along the following lines to work:
> temp.name <- paste(TimePt,'df',sep='.') # invent a relevant name/symbol as a
> character string.
> assign(temp.name,IGF.df[IGF.df$TPt==TimePt,]) # this works. The relevant
> variable is now a data frame
> lm(b ~ Strain+BWt+PWt+PanPix, data=temp.name)) # this gives an error, namely
> Error in eval(predvars, data, env) : invalid 'envir' argument
>
> I think it's obvious what I want to achieve, but how is it done? I tried
> data=as.name(temp.name)
> but that also didn't work. I can't find anything relevant in "Introduction
> to R".
>   

That's because constructing names like this is generally a bad idea.  
But you can do it; you use get() to get the object whose name is in 
temp.name.  So put data=get(temp.name) into your lm() call.

> Here is a secondary question:
> While trying to understand what assign() does, I looked up help(assign) and
> found the example
> a <- 1:4
> assign("a[1]", 2)
>   

This creates an object with name "a[1]".  That's not usually a legal 
name, but assign() can still create a variable with that name.
> a[1] == 2          #FALSE
>   

This tries to find the 1st element of an object named a.
> get("a[1]") == 2   #TRUE
>   

This gets the object with the weird name.

> Could someone explain this puzzling example, or point me to an explanation
> of environments and how to operate with them?
>   

See the R Language Definition.  There's a section on environments, and 
mention of them in a number of other places.

Duncan Murdoch
> Thanks
>
>
>



More information about the R-help mailing list