将Anova结果写入文本文件

时间:2017-06-26 13:19:09

标签: r

我尝试将一个Anova结果写入txt。但是,我发现写函数无法处理任务。

我的代码如下:

##first I calculate the Anova of two variable and then stored the result in "a".
functionanova<-function(x,y,datasource){
result= aov(y ~ x, data= datasource)
return(summary(result))
}

a<-functionanova(df1$Pe,df1$Pb,df1)

##The result is:
a
            Df Sum Sq Mean Sq F value Pr(>F)
x            1   2.77   2.773   0.662  0.419
Residuals   68 284.85   4.189      

> class(a)
[1] "summary.aov" "listof"     

##Then I try to write it to an text. However,there is an error with this type of data.
> write(a, "d:\\week1\\MYOUTFILE.txt", append= TRUE,sep = " ")
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'
##I try to convert it to a data frame. However, there is also an error with it.
> aa<-as.data.frame(a)
Error in as.data.frame.default(a) : 
cannot coerce class "c("summary.aov", "listof")" to a data.frame

1 个答案:

答案 0 :(得分:3)

使用capture.output

a<-functionanova(df1$Pe,df1$Pb,df1)
capture_a <- summary(a)
capture.output(capture_a, file = "anova results.txt")