[R] Extracting an object name?

Gabor Grothendieck ggrothendieck at gmail.com
Sat Apr 25 13:12:33 CEST 2009


On Sat, Apr 25, 2009 at 6:56 AM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 24/04/2009 9:30 PM, greggallen at gmail.com wrote:
>>
>> Dear Sir or Madam:
>>
>> This is an extension to a earlier post, about looping through several
>> thousand files, and testing student's models against a different
>> data-set, called rclnow, for "recall now".
>>
>> The problem is, that the instructor never specified to the students,
>> what they should name their "lm" object.
>>
>> So what they created was:
>> "arbitrary variable name" <- lm(Y~(V1+V2+.... more stuff),
>> learn_data_frame)
>>
>> Now there are 1500+ files that are named:
>> "BIOtotals_students_name_class_name_date_other_info..."
>> "BIOtotals_more_stuff_2.."
>> "BIOtotal_more-stuff_3
>> ......................
>> ......................
>>
>>
>> Now I always get this error in the "predict" statement:
>>
>> Error in UseMethod("predict") : no applicable method for "predict"
>>
>> Is there a way to pass the unknown object name to predict, or do we
>> need to ask the students to redo all the work with a given model name?
>> (I hope not!)
>
> predict() doesn't want an object name, it wants an object.  load() returns
> an object name, and loads the object.  So you can find the object by the
> name that gets loaded.
>
> If the students only created one object, you could do it as
>
> name <- load(s)
> model <- get(name)
>
> but that's dangerous:  if you don't know what the student named the model,
> then you don't want to load it in with all your other variables.  So a safer
> way to go is:
>
> studentvars <- new.env()
> names <- load(s, studentvars)
>
> Now figure out which of the names is the model (say names[1]), and do
> model <- get(names[1], envir=studentvars)

A variation of this would be:

studentvars <- new.env()
L <- as.list(studentvars)[eapply(e, class) == "lm"]

if (length(L) != 1) cat("warning: there are", length(L), "objects --
should be 1\n")
else  model <- L[[1]]


which would give you the first object of class "lm" so any non-lm
objects won't erroneously be retrieved.  The onl




More information about the R-help mailing list