在控制台R中从print创建矩阵

时间:2014-01-22 01:08:18

标签: r matrix

我的代码仅在控制台中打印公式的结果。此代码中有for和if循环。

如何为要整理的数据创建矩阵?

1 个答案:

答案 0 :(得分:0)

这是一个运行两个回归的示例,提取结果,并将结果存储在名为outcomes的数据框中。

library(plyr)
library(arm)
# create some data
  dat <- data.frame(group=c(rep(1, 30), rep(0, 30)),
                    dv1=runif(60, 1, 30),
                    dv2=runif(60, 1, 30),
                    iv1=sample(c(0:1), 60, replace=TRUE),
                    iv2=runif(60, 1, 30))
# dvs to test
  dv <- c("dv1", "dv2")
# create object to receive results
  outcomes <- NULL
  outcomes <- as.data.frame(outcomes)
# for loop
  for (i in 1:length(dv)) {
    # run a regression and store the results
      temp <- lm(get(dv[i]) ~ group + factor(iv1) + iv2, data=dat)
      temp2 <- summary(temp)
    # extract results and fill table
      outcomes[i,1] <- dv[i]                    # name of outcome variable
      outcomes[i,2] <- display(temp)$n          # total observations
      treat.n <- count(dat$group, 1)[2,2]       # obs in treatment group
      control.n <- count(dat$group, 1)[1,2]
      treat.m <- aggregate(dat[dv[i]],          # treatment mean
                           by=list(dat$group), 
                           FUN=mean, 
                           na.rm=TRUE)[2,2]
      outcomes[i,3] <- treat.m
      treat.sd <- aggregate(dat[dv[i]],         # treatment sd
                            by=list(dat$group), 
                            FUN=sd, 
                            na.rm=TRUE)[2,2]
      outcomes[i,4] <- treat.sd
      control.m <- aggregate(dat[dv[i]],        # control mean    
                             by=list(dat$group), 
                             FUN=mean, 
                             na.rm=TRUE)[1,2]
      outcomes[i,5] <- control.m                   
      control.sd <- aggregate(dat[dv[i]],       # control sd
                              by=list(dat$group), 
                              FUN=sd, 
                              na.rm=TRUE)[1,2]
      outcomes[i,6] <- control.sd
      coeffs <- coefficients(temp)              # coefficients
      outcomes[i,7] <- coeffs[2]                # ATE
      outcomes[i,8] <- se.coef(temp)[2]         # std err
      outcomes[i,9] <- coef(temp2)[,4][2]       # p-value
    # add column names
      names(outcomes) <- c("variable", "obs", "treat.mean", "treat.sd", 
                           "control.mean", "control.sd", "ate", "ate.se",
                           "pvalue")
  }