功能中找不到对象错误

时间:2013-06-25 14:13:30

标签: r function ggplot2

我已经制作了这个函数,用于输出ANCOVA的摘要并绘制结果:

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))

}

如果我尝试使用这样的功能:

statAncova(mtcars, drat, hp, cyl)

我收到此错误:

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

我做错了什么?

1 个答案:

答案 0 :(得分:3)

R期望在环境中有一个名为'drat'的对象,但'drat'是数据帧mtcars的成员。

我知道可能有一个更优雅的解决方案,但解决这个问题的一种方法是使用:

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")

或者,您可以传递您感兴趣的各个变量:

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)