Search code examples
rfunctionobjectparameter-passinggam

Error in seq(min(x), max(x), length = timesteps) : object 'a' not found within function


I'm trying to build a function that will plot my results. The second line in the function will give me the following error:

Error in seq(min(x), max(x), length = timesteps) : object 'a' not found'

Clearly a and b exist, because the gam is able to read them in, and the first line of the function works perfectly fine, too. When I use the code outside the function, it also works... I don't know what I'm missing there.

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)

Solution

  • Please check if this works. I just overwrote all your function:

    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)