Prasinus Albus
Prasinus Albus

Reputation: 416

lme within a user defined function in r

I need to use mixed model lme function many times in my code. But I do not know how to use it within a function. If used otherwise, the lme function works just well but when used within the function, it throws errors:

myfunc<- function(cc, x, y, z)
{

    model <- lme(fixed = x ~1 , random = ~ 1|y/z,
    data=cc,
    method="REML")
}

on calling this function: myfunc (dbcon2, birthweight, sire, dam)

I get the error :

Error in model.frame.default(formula = ~x + y + z, data = list(animal = c("29601/9C1", : invalid type (list) for variable 'x'

I think, there is a different procedure for using this which I am unaware of. Any help would be greatly appreciated.

Thanks in advance

Upvotes: 2

Views: 1289

Answers (1)

PKumar
PKumar

Reputation: 11128

Not sure if you are looking for this, you may try to use this, as correctly pointed out by @akrun, you may use paste, I am using paste0 however(its a special case of paste), paste concatenates two strings:

Here the idea is to concatenate the variable names with the formula, but since paste converts it to a string hence you can't refer that as formula to build a model,so you need to convert that string to a formula using as.formula which is wrapped around paste0 statement.

To understand above, Try writing a formula like below using paste:

formula <-paste0("mpg~", paste0("hp","+", "am"))
print(formula)
[1] "mpg~hp+am"
class(formula)
[1] "character" ##This should ideally be a formula rather than character
formula <- as.formula(formula) ##conversion of character string to formula
class(formula)
[1] "formula"

To work inside a model, you would always require a formula object, also please also try to learn about collapse and sep option in paste they are very handy.

I don't have your data , hence I have used mtcars data to represent the same.

library("nlme")
myfunc<- function(cc, x, y, z)
{

model <- lme(fixed = as.formula(paste0(x," ~1")) , random = as.formula(paste0("~", "1|",y,"/",z)),
               data=cc,
               method="REML")
}
models <- myfunc(cc=mtcars, x="hp", y="mpg", z="am")

summary(models)

You can read more about paste by typing ?paste in your console.

Upvotes: 2

Related Questions