2013-06-25 443 views
3

我做了這個功能,其目的是輸出的協方差分析的總結得出結果:未找到對象錯誤功能

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 

我在做什麼錯?

+5

這裏有更多的基本問題,主要是R根本不會識別「響應」,「協變量」或「因子」。您必須將它們作爲字符串傳遞,並手動構建任何公式。 – joran

回答

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)