Using objects within functions in formulas
David Winsemius <dwinsemius <at> comcast.net> writes:
On Jan 9, 2013, at 8:53 AM, Aidan MacNamara wrote:
I'm looking to create a formula within a function to pass to glmer()
and I'm having a problem that the following example will illustrate:
library(lme4)
y1 = rnorm(10)
x1 = data.frame(x11=rnorm(10), x12=rnorm(10), x13=rnorm(10))
x1 = data.matrix(x1)
w1 = data.frame(w11=sample(1:3,10, replace=TRUE), w12=sample(1:3,10,
replace=TRUE), w13=sample(1:3,10, replace=TRUE))
test1 <- function(x2, y2, w2) {
print(str(w2))
form = as.formula(paste("y2 ~ x2 +" ,paste("(1|w2$", names(w2), ")",
collapse=" + ", sep="")))
m1 = glmer(form)
return(m1)
}
model1 = test1(x2=x1, y2=y1, w2=w1)
As can be seen from the print statement within the function, the
object "w2" is present and is a data frame. However, the following
error occurs:
Error in is.factor(x) : object 'w2' not found
[snip David's solution to try to make gmane happy about the amount of quoted material]
This can be rectified by making 'w2' global - defining it outside the function. I know there are issues with defining formulas and environment but I'm not sure why this problem is specific to 'w2' and not the other objects passed to the function. Any help would be appreciated. Aidan MacNamara EMBL-EBI
I haven't had a chance to look at this, but I will try to get to it. It would help if you could post it on the "Issues" page of the lme4 github site, https://github.com/lme4/lme4/ . The bottom line is that dealing appropriately with all the different possible ways to assign and evaluate variables within formulas is trickier than I would like it to be. To the best of my knowledge I have solved most of these problems in the development version of lme4, but another test case will be useful. As long as there is a reasonable workaround I'm unlikely to put the effort into fixing the stable version of lme4 (sorry ...) Follow-ups to r-sig-mixed-models at r-project.org or (preferably) to the aforementioned "Issues" list. Ben Bolker