3
votes

I've made this function which is intended to output the summary of an ANCOVA and plot the results:

statAncova <- function (dataframe, response, covariate, Factor) {

  library(ggplot2)
  mod <- aov(response ~ covariate + Factor, data=dataframe)
  pred <- predict(mod)
  plotMod <- ggplot(data = cbind(mod$model, pred), aes(covariate, response, color=Factor)) + 
    geom_point() +
    facet_grid(. ~ Factor) + 
    geom_line(aes(y=pred))

  return(list(mod, plotMod))

}

If I try to use function like this:

statAncova(mtcars, drat, hp, cyl)

I get this error:

Error in eval(expr, envir, enclos) : object 'drat' not found

What am I doing wrong?

1
There are more fundamental issues here, mainly that R won't recognize response, covariate or Factor at all. You'll have to pass them as character strings, and construct any formulas by hand. - joran

1 Answers

3
votes

R is expecting for there to be an object called 'drat' in the environment, but 'drat' is a member of the data frame mtcars.

I know there's probably a more elegant solution, but one way to fix it would be to use:

statAncova <- function (dataframe, response, covariate, Factor) {

  library(ggplot2)
  eval(parse(text=paste0("mod <- aov(",response," ~ ",covariate," + ",Factor,", data=dataframe)")))
  pred <- predict(mod)
  eval(parse(text=paste0("plotMod <- ggplot(data = cbind(mod$model, pred), aes(",covariate,", ",response,", color=",Factor,")) + 
  geom_point() +
  facet_grid(. ~ ",Factor,") + 
  geom_line(aes(y=pred))")))

  return(list(mod, plotMod))

}

statAncova(mtcars, "drat", "hp", "cyl")

Alternatively, you could just pass the individual variables that you're interested in:

statAncova <- function (response, covariate, Factor) {

  dataframe <- data.frame(response, covariate, Factor)

  library(ggplot2)
  mod <- aov(response ~ covariate + Factor, data=dataframe)
  pred <- predict(mod)
  plotMod <- ggplot(data = cbind(mod$model, pred), aes(covariate, response, color=Factor)) + 
    geom_point() +
    facet_grid(. ~ Factor) + 
    geom_line(aes(y=pred))

  return(list(mod, plotMod))

}

statAncova(mtcars$drat, mtcars$hp, mtcars$cyl)