[R] puzzles with assign()
murdoch.duncan at gmail.com
Wed May 5 13:36:50 CEST 2010
> 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
> 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", 2)
This creates an object with name "a". That's not usually a legal
name, but assign() can still create a variable with that name.
> a == 2 #FALSE
This tries to find the 1st element of an object named a.
> get("a") == 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.
More information about the R-help