0

我有一个要从中提取系数的嵌套模型列表,然后创建一个数据框,其中每一行还包含存储该模型的列表元素的名称。我想知道是否有一个 plyr 函数已经处理了嵌套列表,或者只是一种更清洁的方式来完成任务。

例如:

### Create nested list of models

iris.models <- list()
for (species in unique(iris$Species)) {

iris.models[[species]]<- list()

for (m in c("Sepal.Length","Sepal.Width","Petal.Length")) {

    iris.formula <- formula(paste("Petal.Width ~ ", m))
    iris.models[[species]][[m]] <- lm(iris.formula
                                      , data=iris
                                      , subset=Species==species)

    } # for m

} # for species 

### Create data frame of variable coefficients (excluding intercept)

irisCoefs <- ldply(names(iris.models)
             , function(sp) {
              ldply(iris.models[[sp]]
                    , function(meas) data.frame(Species=sp, Coef=coef(meas)[-1])
            )})
colnames(irisCoefs)[colnames(irisCoefs)==".id"] <- "Measure"
irisCoefs

此代码生成如下数据框:

  Measure      Species          Coef
1 Sepal.Length setosa     0.08314444
2 Sepal.Width  setosa     0.06470856
3 Petal.Length setosa     0.20124509
4 Sepal.Length versicolor 0.20935719
5 Sepal.Width  versicolor 0.41844560
6 Petal.Length versicolor 0.33105360
7 Sepal.Length virginica  0.12141646
8 Sepal.Width  virginica  0.45794906
9 Petal.Length virginica  0.16029696

虽然我的代码有效,但我最终这样做的方式似乎有点不雅,我想知道我是否可以进一步简化它(或将其推广到其他情况):

我的问题是:

使用嵌套列表似乎有点棘手。在外部 ldply 调用中,我必须使用列表项的名称,但在内部调用中,我得到了“免费”添加的 .id 列。我想不出一种更简单的方法来访问被调用函数中列表元素的名称。

我也无法在第二个 ldply 函数调用本身中更改“.id”中的列名。所以我最终在之后添加了 colnames 语句。

有没有办法让我的代码在 plyr 做事方式中更直接?

我不知道这是否有助于澄清我的意图,但我想象代码看起来像:

ldply(iris.models, .id.col="Species", function(sp) ldply(sp, .id.col="Measure", function(x) data.frame(coef(x)[-1])))

谢谢。

4

2 回答 2

0

不完全是所需的格式,但这适用于基本功能。

m=c("Sepal.Length","Sepal.Width","Petal.Length")
do.call(rbind,
    by(iris,iris$Species,
      function(x) sapply(m, 
        function(y) coef(lm(paste('Petal.Width ~',y),data=x))) [2,]
   ) 
)

           Sepal.Length Sepal.Width Petal.Length
setosa       0.08314444  0.06470856    0.2012451
versicolor   0.20935719  0.41844560    0.3310536
virginica    0.12141646  0.45794906    0.1602970
于 2012-08-17T19:17:22.593 回答
0

plyr 方法:

#Melt the predictor variables
iris_m <- melt(iris[, -4], id.vars = "Species")
#Insert the dependant variable
iris_m$Petal.Width <- rep(iris$Petal.Width, 3)

#Make the models divide by species and variable
models <- dlply(iris_m, .(Species, variable), 
                function(x) lm(Petal.Width ~ value, data = x))
#Get the coefficients as a nice data.frame
ldply(models, function(x) coef(x)[-1])

     Species     variable      value
1     setosa Sepal.Length 0.08314444
2     setosa  Sepal.Width 0.06470856
3     setosa Petal.Length 0.20124509
4 versicolor Sepal.Length 0.20935719
5 versicolor  Sepal.Width 0.41844560
6 versicolor Petal.Length 0.33105360
7  virginica Sepal.Length 0.12141646
8  virginica  Sepal.Width 0.45794906
9  virginica Petal.Length 0.16029696
于 2012-08-17T18:52:28.897 回答