我正在尝试构建一个能够绘制结果的函数。函数中的第二行将给出以下错误:
seq中的错误(min(x),max(x),length = timesteps):对象'a'未找到'
显然a和b存在,因为gam能够读取它们,并且该函数的第一行也能很好地工作。当我在函数外部使用代码时,它也可以工作......我不知道我在那里缺少什么。
library(mgcv)
library(ggplot2)
theme_set(theme_bw())
set.seed(100)
dd <- data.frame(a=1:100,b=round(rnorm(100,mean=100),1))
m <- gam(formula = b ~ s(a, k = 64, bs = "ad"), data = dd, method = "REML", select = TRUE)
plot<-function(model,x,y,timesteps){
ggplot(model, aes_string(x = deparse(substitute(x)), y=deparse(substitute(y)))) + geom_point()
pred <- with(model, data.frame(x = seq(min(x), max(x), length = timesteps)))
# Error in seq(min(x), max(x), length = timesteps) : object 'a' not found
pred <- cbind(pred, as.data.frame(predict(m, pred, se.fit = TRUE, unconditional = TRUE)))
pred <- transform(pred,
Fitted = fit,
Upper = fit + (2 * se.fit),
Lower = fit - (2 * se.fit))
ggplot(model, aes(x = x, y=y)) +
geom_point() +
geom_ribbon(data = pred, mapping = aes(x = x, ymin = Lower, ymax = Upper),
fill = "#9ecf7f", colour = NA, alpha = 0.7, inherit.aes = FALSE) +
geom_path(data = pred, mapping = aes(x = x, y = Fitted), inherit.aes = FALSE,
size = 1)
}
plot(dd,a,b,64)
答案 0 :(得分:2)
请检查一下是否有效。我刚刚覆盖了你所有的功能:
plot <- function(model, x, y, timesteps){
library(ggplot2)
# Use get instead of aes_string
ggplot(model, aes(get(x), get(y))) +
geom_point()
# To extract min X value we'll use it's position in data frame
whichX <- colnames(model) == x
pred <- data.frame(seq(min(model[, whichX]), max(model[, whichX]),
length = timesteps))
colnames(pred) <- x
pred <- cbind(pred, as.data.frame(predict(m, pred, se.fit = TRUE, unconditional = TRUE)))
pred <- transform(pred,
Fitted = fit,
Upper = fit + (2 * se.fit),
Lower = fit - (2 * se.fit))
ggplot(model, aes(get(x), get(y))) +
geom_point() +
geom_ribbon(data = pred, mapping = aes(x = get(x), ymin = Lower, ymax = Upper),
fill = "#9ecf7f", colour = NA, alpha = 0.7, inherit.aes = FALSE) +
geom_path(data = pred, mapping = aes(x = get(x), y = Fitted), inherit.aes = FALSE,
size = 1)
}
# quote your variables before passing them
# e.g.: a is not defined and you have to "a"
plot(dd, "a", "b", 64)