2014-01-22 120 views
0

我只在控制檯中輸入了公式的結果。此代碼中有和如果循環。從控制檯R中的打印創建矩陣R

如何爲要整理的數據創建矩陣?

+0

所以你有文本表示的數據?如果是這樣,它是什麼樣子?如果不是,你到底是什麼? –

+0

歡迎來到SO。看看[R介紹](http://cran.r-project.org/doc/manuals/R-intro.pdf),如果你仍然懷疑嘗試做一個例子,並提出一個問題代碼在裏面。 – marbel

回答

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") 
    } 
+0

這與這個問題有什麼關係? –

+0

OP說他/她有一個公式和循環,打印結果到控制檯和他/他想要在矩陣中捕獲結果。我創建了一個玩具數據集,並在迴路中運行迴歸並將結果提取到數據框中。總體思路可以應用於OP的實際問題。 –