Why does get fail to find object in gamm, yet it works in lm?

322 views Asked by At

I am struggling with writing an R function that calls a variable using get()

Suppose I have this data frame:

mydat = data.frame(y = rnorm(100), 
                   x = rnorm(100), 
                   day = sample(90:260, 100, replace = T), 
                   r1 = sample(seq(2008,2015,1), 100, replace = T),
                   r2 = sample(letters, 100, replace = T), 
                   r3 = sample(letters, 100, replace = T))

and I would like to write a function that returns the summary of a gamm model, e.g like this

gamm_summary = function(data, response = "y"){
    require(mgcv)
    gamm_model = gamm(get(response) ~ s(day),
                      random = list(r1=~1, r2=~1, r3 =~1), data = data, method = "REML")

    summary(gamm_model$gam)
}


gamm_summary(mydat)

Why does this give me the error:

Error in get(response) : object 'response' not found

yet the following works:

lm_summary = function(data, response = "y") {
    lm_model = lm(get(response) ~ x, data = data)
    summary(lm_model)
}

lm_summary(mydat)

Q: Why does get fail to work in my gamm function and how could I rewrite the function so that it works?

1

There are 1 answers

1
d.b On BEST ANSWER
require(mgcv)
gamm_summary = function(mydata, a1 = "y", b1 = "day", rnd1 = "r1", rnd2 = "r2", rnd3 = "r3"){
    df = data.frame(aa = mydata[[a1]], bb = mydata[[b1]], rnd1 = mydata[[rnd1]], rnd2 = mydata[[rnd2]], rnd3 = mydata[[rnd3]])
    gamm_model = gamm(aa ~ s(bb), data = df, random = list(rnd1 =~ 1, rnd2 =~ 1, rnd3 =~ 1), method = "REML")
    summary(gamm_model$gam)
}

gamm_summary(mydat, a1 = "x")