tags:

views:

97

answers:

1

I'm using the package glmulti to fit models to several datasets. Everything works if I fit one dataset at a time.

So for example:

output <- glmulti(y~x1+x2,data=dat,fitfunction=lm) 

works just fine.

However, if I create a wrapper function like so:

analyze <- function(dat)
{
out<- glmulti(y~x1+x2,data=dat,fitfunction=lm)
return (out)
}

simply doesn't work. The error I get is

error in evaluating the argument 'data' in selecting a method for function 'glmulti'

Unless there is a data frame named dat, it doesn't work. If I use results=lapply(list_of_datasets, analyze), it doesn't work. So what gives? Without my said wrapper, I can't lapply a list of datasets through this function. If anyone has thoughts or ideas on why this is happening or how I can get around it, that would be great.

example 2:

dat=list_of_data[[1]]
analyze(dat)

works fine. So in a sense it is ignoring the argument and just literally looking for a data frame named dat. It behaves the same no matter what I call it.

+4  A: 

I guess this is -yet another- problem due to the definition of environments in the parse tree of S4 methods (one of the resons why I am not a big fan of S4...)

It can be shown by adding quotes around the dat :

> analyze <- function(dat)
+ {
+ out<- glmulti(y~x1+x2,data="dat",fitfunction=lm)
+ return (out)
+ }
> analyze(test)
Initialization...
Error in eval(predvars, data, env) : invalid 'envir' argument

You should in the first place send this information to the maintainers of the package, as they know how they deal with the environments internally. They'll have to adapt the functions.

A -very dirty- workaround for yourself, is to put "dat" in the global environment and delete it afterwards.

analyze <- function(dat)
{
assign("dat",dat,envir=.GlobalEnv)  # put the dat in the global env
out<- glmulti(y~x1+x2,data=dat,fitfunction=lm)
remove(dat,envir=.GlobalEnv) # delete dat again from global env
return (out)
}

EDIT: Just for clarity, this is really about the worst solution possible, but I couldn't manage to find anything better. If somebody else gives you a solution where you don't have to touch your global environment, by all means use that one.

Joris Meys
Thanks a ton Joris. I really must sit down and bone up on S4 methods. At least for now I can see how this workaround behaves. cheers.
Maiasaura
It behaves well, as long as you don't have an object called "dat" in your workspace. If so, that one will be overwritten by the assign() function. That's something you definitely want to avoid...
Joris Meys
Not the S4 and .GlobalEnv again :slap on the forehead:.
Roman Luštrik