【问题标题】:Using some sort of bind() function to create a data.frame with coefficients from nested models?使用某种 bind() 函数创建一个带有嵌套模型系数的 data.frame?
【发布时间】:2012-07-26 09:47:10
【问题描述】:

我认为我的想法不错,但不知道如何实施。我目前正在运行许多嵌套模型。例如:

y<-c(1, 0, 1, 1, 1, 1, 1, 1, 0)
x1<-c(1, 0, 9, 9, 1, 9, 2, 1, 0)
x2<-c(1, 2, 3, 5, 4, 2, 4, 5, 1)
x3<-c(1, 2, 1, 4, 1, 3, 4, 8, 3)

model1 <-lm(y~x1)
model2 <-lm(y~x1+x2)
model3 <-lm(y~x1+x2+x3)

model1_output<-(summary(model1 )$coefficients[1])
model2_output<-(summary(model1 )$coefficients[1])
model3_output<-(summary(model1 )$coefficients[1])

然后,我想将我的所有输出放在一个数据表中,该数据表沿行(变量名)匹配,但将新系数插入到它们自己的列中。我希望 data.frame 将我的示例的输出显示为:

             b(Model 1)  b(Model 2) b(Model 3)
 (Intercept)  0.59217    0.2555     0.27983
 x1           0.05220    0.04116    0.0375
 x2              NA      0.12530    0.15142
 x3              NA      NA        -0.02994

我确信一定有一些聪明的方法可以使用 plyr() 包(或其他包!)来做到这一点,但似乎无法弄清楚。谢谢!

【问题讨论】:

标签: r


【解决方案1】:

在另一个问题中使用这个answer

cbind.fill<-function(...){
    nm <- list(...) 
    nm<-lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow)) 
    do.call(cbind, lapply(nm, function (x) 
    rbind(x, matrix(, n-nrow(x), ncol(x))))) 
}

你可以这样做:

do.call(cbind.fill,lapply(list(model1,model2,model3),function(x){coef(x)}))

                  [,1]       [,2]        [,3]
(Intercept) 0.59216966 0.25551154  0.27982881
x1          0.05220228 0.04116431  0.03754457
                    NA 0.12530141  0.15142340
                    NA         NA -0.02993768

然后手动设置行列名。 (请注意,如果这对您很重要,这将返回一个矩阵,而不是数据框。)

【讨论】:

  • 快速问题——如何添加与我的系数相关的多个列?我试过:do.call(cbind.fill,lapply(list(model1,model2,model3),function(x){coef[1:4](x)})),但这似乎不起作用。
【解决方案2】:

试试下面的。我尽量保持一般性,并从here 那里借了一些帮助。

models <- list(model1=model1,model2=model2,model3=model3)    

#Find out which model (by index) has the most coefficients.
max.model <- which.max(unlist(lapply(models, function(x) length(x[[1]]))))

#How many coefficients there are in the 'biggest' model (including intercept)
max <- length(models[[max.model]][[1]])

#Create list of coefficients, replacing blank spaces with NA
coeff <- lapply(models, function(x) c(x[[1]],rep(NA,max-length(x[[1]]))))

#See the link above
result <- do.call(cbind,coeff)

colnames(result) <- names(models)

rownames(result) <- names(models[[max.model]][[1]])

结果:

> result
                model1     model2      model3
(Intercept) 0.59216966 0.25551154  0.27982881
x1          0.05220228 0.04116431  0.03754457
x2                  NA 0.12530141  0.15142340
x3                  NA         NA -0.02993768

我试图保持通用的意思是,这适用于任何数量的模型;只需要修改第一行代码。

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多