R:使用聚合作为矩阵参数的函数

时间:2017-05-02 01:25:19

标签: r

我想对每个类使用mutlivariate能量测试,如下例所示:

require(energy)
aggregate(formula = .~Species, FUN = function(x, R) (mvnorm.etest(as.matrix(x), R = R)$p.value), data = iris, R = 999) 

但是,有一个错误:

Error in P %*% diag(1/sqrt(lambda)) : non-conformable arguments

有没有办法一次性完成这项工作?

感谢您对此问题的任何帮助!

1 个答案:

答案 0 :(得分:0)

这是我提出的一种不使用聚合的方法:

lapply(split(iris, iris$Species), function(x) mvnorm.etest(x[, -5], 999))
$setosa

    Energy test of multivariate normality: estimated parameters

data:  x, sample size 50, dimension 4, replicates 999
E-statistic = 1.2034, p-value = 0.03604


$versicolor

    Energy test of multivariate normality: estimated parameters

data:  x, sample size 50, dimension 4, replicates 999
E-statistic = 1.084, p-value = 0.1502


$virginica

    Energy test of multivariate normality: estimated parameters

data:  x, sample size 50, dimension 4, replicates 999
E-statistic = 1.0219, p-value = 0.3233

以下是我使用dplyrbroom软件包的tidy函数提出的另一种方法,可以将结果组织到数据框中。

library(dplyr)
library(broom)
iris %>%
  group_by(Species) %>%
  do(tidy(mvnorm.etest(select(., -Species), 999)))

Source: local data frame [3 x 4]
Groups: Species [3]

     Species statistic    p.value                                                      method
      <fctr>     <dbl>      <dbl>                                                      <fctr>
1     setosa  1.203397 0.03303303 Energy test of multivariate normality: estimated parameters
2 versicolor  1.083996 0.16916917 Energy test of multivariate normality: estimated parameters
3  virginica  1.021852 0.31431431 Energy test of multivariate normality: estimated parameters

希望这会有所帮助。如果你必须使用聚合,我可以弄清楚它为什么不起作用。