[R] Using objects within functions in formulas

Aidan MacNamara aidan.macnamara at gmail.com
Wed Jan 9 17:53:11 CET 2013

Dear all,

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:

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) {

	form = as.formula(paste("y2 ~ x2 +" ,paste("(1|w2$", names(w2), ")",
collapse=" + ", sep="")))
	m1 = glmer(form)

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

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

More information about the R-help mailing list