[R] Using objects within functions in formulas

Aidan MacNamara aidan.macnamara at gmail.com
Thu Jan 10 08:55:52 CET 2013


Thanks everyone, very helpful.

On 9 January 2013 18:33, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Jan 9, 2013, at 8:53 AM, Aidan MacNamara wrote:
>
>> 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:
>>
>> 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
>
>
> Generally regression functions in R will be expecting to get one 'data'
> argument and build formulas using column names from that object.
>
>
>  test1 <- function(x2, y2, w2) {
>    w3 <- cbind(w2, x2, x2)
>         print(str(w3))
>         form = as.formula(paste("y2 ~ x2 +" ,paste("(1|", names(w2), ")",
>
> collapse=" + ", sep="")))
>         m1 = glmer(form, data=w3); print(summary(m1))
>
>         return(m1)
>     }
>
> model1 = test1(x2=x1, y2=y1, w2=w1)
>
>
>>
>> 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
>>
>
>
> David Winsemius, MD
> Alameda, CA, USA
>




More information about the R-help mailing list