从r中的aov对象中提取均方值的最佳方法

时间:2009-09-14 19:34:27

标签: r statistics

我正在尝试编写一个自动执行方差分析的函数,其中一部分涉及进行一些进一步的计算。我一直在使用的方法不是很健壮,如果变量名称发生变化,那么它就会停止工作。

对于这个虚拟数据

> dput(assayvar,"")
structure(list(Run = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L, 4L, 4L, 4L), .rk.invalid.fields = list(), .Label = c("1", 
"2", "3", "4"), class = "factor"), Actual = c(246.3, 253.6, 247.6, 
249, 249, 251.3, 254.9, 254.1, 253.2, 250, 248.9, 250.3)), .Names = c("Run", 
"Actual"), row.names = c(NA, 12L), class = "data.frame")

> assayaov<-aov(Actual~Run+Error(Run),data=assayvar)
> str(summary(assayaov))
List of 2
 $ Error: Run   :List of 1
  ..$ :Classes ‘anova’ and 'data.frame':    1 obs. of  3 variables:
  .. ..$ Df     : num 3
  .. ..$ Sum Sq : num 46.5
  .. ..$ Mean Sq: num 15.5
  ..- attr(*, "class")= chr [1:2] "summary.aov" "listof"
 $ Error: Within:List of 1
  ..$ :Classes ‘anova’ and 'data.frame':    1 obs. of  5 variables:
  .. ..$ Df     : num 8
  .. ..$ Sum Sq : num 36.4
  .. ..$ Mean Sq: num 4.55
  .. ..$ F value: num NA
  .. ..$ Pr(>F) : num NA
  ..- attr(*, "class")= chr [1:2] "summary.aov" "listof"
 - attr(*, "class")= chr "summary.aovlist"

但对于这个虚拟数据

> dput(BGBottles,"")
structure(list(Machine = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L, 4L, 4L, 4L), .rk.invalid.fields = structure(list(), .Names = character(0)), .Label = c("1", 
"2", "3", "4"), class = "factor"), Weight = c(14.23, 14.96, 14.85, 
16.46, 16.74, 15.94, 14.98, 14.88, 14.87, 15.94, 16.07, 14.91
)), .Names = c("Machine", "Weight"), row.names = c(NA, 12L), class = "data.frame")

> bgaov<-aov(Weight~Machine+Error(Machine),data=BGBottles)
> str(summary(bgaov))
List of 2
 $ Error: Machine:List of 1
  ..$ :Classes ‘anova’ and 'data.frame':    1 obs. of  3 variables:
  .. ..$ Df     : num 3
  .. ..$ Sum Sq : num 5.33
  .. ..$ Mean Sq: num 1.78
  ..- attr(*, "class")= chr [1:2] "summary.aov" "listof"
 $ Error: Within :List of 1
  ..$ :Classes ‘anova’ and 'data.frame':    1 obs. of  5 variables:
  .. ..$ Df     : num 8
  .. ..$ Sum Sq : num 1.45
  .. ..$ Mean Sq: num 0.182
  .. ..$ F value: num NA
  .. ..$ Pr(>F) : num NA
  ..- attr(*, "class")= chr [1:2] "summary.aov" "listof"
 - attr(*, "class")= chr "summary.aovlist"

所以得到均方值的代码

machine<-summary(bgaov)$"Error: Machine"[[1]]$"Mean Sq"

不起作用,因为机器但不一定是机器。

有更好的方法吗?

1 个答案:

答案 0 :(得分:10)

> summary(assayaov)[1][[1]][[1]][[3]]
[1] 15.49
> summary(bgaov)[1][[1]][[1]][[3]]
[1] 1.776475