我正在努力编写一个使用get()
假设我有这个数据框:
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))
我想写一个返回gamm模型摘要的函数,比如这个
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)
为什么这会给我错误:
get(响应)错误:找不到对象'响应'
但以下工作:
lm_summary = function(data, response = "y") {
lm_model = lm(get(response) ~ x, data = data)
summary(lm_model)
}
lm_summary(mydat)
问:为什么我的gamm函数无法工作?如何重写函数以使其有效?
答案 0 :(得分:2)
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")