R在新文档的列中存储来自大量汇总表的变量

时间:2015-11-17 14:31:10

标签: r csv summary r-package

我有一个包含6列的数据框(X):mean.x,s.x,n.x,mean.y,s.y,n.y。它们代表来自群体x和y的平均值,st dev(s)和样本大小(n)。我正在运行一个R包(BSDA),它根据这些统计参数执行t检验。问题是,对于每一行,我得到1个汇总表,我有640.000行。

我想要做的是创建包含640.000汇总表中所有p值和其他参数的新列。这可能吗?

前5行的值相同:mean.x(0.444357),sx(0.02575427),nx(633744),mean.y(0.4308),sy(0.000628747),ny(390)

这是显示摘要表的脚本:

library(BSDA)

tsum.test(mean.x = X$mean.x,
          s.x = X$s.x,
          n.x = X$n.x,
          mean.y = X$mean.y,
          s.y = X$s.y,
          n.y = X$n.y, 
          alternative = "less",
          mu = 0, # null hypothesis that there is no diff between means
          var.equal = FALSE,
          conf.level = 0.95)

非常感谢!

1 个答案:

答案 0 :(得分:1)

可能是的。看看下面。一种方法是使用apply

想象一下这样一个非常简单的data.frame(对于这个简单的例子,所有行都是相同的):

x  <- c(7.8, 6.6, 6.5, 7.4, 7.3, 7.0, 6.4, 7.1, 6.7, 7.6, 6.8) 
y  <- c(4.5, 5.4, 6.1, 6.1, 5.4, 5.0, 4.1, 5.5) 
X <- data.frame(mean_x = mean(x), s.x = sd(x), n.x = 11, mean_y = mean(y), s.y = sd(y), 
                n.y = 8) 
X <- rbind(X, X, X)

#> X
#    mean_x       s.x n.x mean_y       s.y n.y
#1 7.018182 0.4643666  11 5.2625 0.7069805   8
#2 7.018182 0.4643666  11 5.2625 0.7069805   8
#3 7.018182 0.4643666  11 5.2625 0.7069805   8

然后,您使用apply在每一行上运行tsum.test,然后提取所需的参数。对于示例,我提取了p.valuesdegrees of freedom

new_cols <-
apply(X, 1, function(x) {

  #using apply in each iteration, a row will be fed to the tsum.test function
  #so make sure you re using the correct ones
  stats <- 
    #x[1] corresponds to the first column, x[2] to the second and so on
    tsum.test(mean.x = x[1],
          s.x = x[2],
          n.x = x[3],
          mean.y = x[4],
          s.y = x[5],
          n.y = x[6], 
          alternative = "less",
          mu = 0, # null hypothesis that there is no diff between means
          var.equal = FALSE,
          conf.level = 0.95)

  #output p.values and degrees of freedom on this occasion
  c(pvalue = stats$p.value, df = stats$parameters)

})  

上面输出了自由度和p.values,为了绑定到你的data.frame,你可以做到:

   > cbind(X, t(new_cols))
    mean_x       s.x n.x mean_y       s.y n.y pvalue.mean_x    df.df
1 7.018182 0.4643666  11 5.2625 0.7069805   8     0.9999669 11.30292
2 7.018182 0.4643666  11 5.2625 0.7069805   8     0.9999669 11.30292
3 7.018182 0.4643666  11 5.2625 0.7069805   8     0.9999669 11.30292