使用R中的聚合函数执行t检验

狗狗说什么

我在使用未配对的t检验和聚合函数时遇到困难。

例子

dd<-data.frame(names=c("1st","1st","1st","1st","2nd","2nd","2nd","2nd"),a=c(11,12,13,14,2.1,2.2,2.3,2.4),b=c(3.1,3.2,3.3,3.4,3.1,3.2,3.3,3.4))
dd
#  Compare all the values in the "a" column that match with "1st" against the values in the "b" column that match "1st".  
#  Then, do the same thing with those matching "2nd"

t.test(c(11,12,13,14),c(3.1,3.2,3.3,3.4))$p.value
t.test(c(3.1,3.2,3.3,3.4),c(3.1,3.2,3.3,3.4))$p.value

#  Also need to replace any errors from t.test that have too low variance with NA
#  An example of the type of error I might run into would be if the "b" column was replaced with c(3,3,3,3,3,3,3,3).  

对于配对的数据,我找到了解决方法。

#  Create Paired data.
data_paired<-dd[,3]-dd[,2]

#  Create new t-test so that it doesn't crash upon the first instance of an error.  
my_t.test<-function(x){
    A<-try(t.test(x), silent=TRUE)
    if (is(A, "try-error")) return(NA) else return(A$p.value)
}

#  Use aggregate with new t-test.  
aggregate(data_paired, by=list(dd$name),FUN=my_t.test)

该汇总适用于单列输入。但是,当我必须在函数中包含几列时,我无法使其正常运行。

例子:

my_t.test2<-function(x,y){
    A<-try(t.test(x,y,paired=FALSE), silent=TRUE)
    if (is(A, "try-error")) return(NA) else return(A$p.value)
}

aggregate(dd[,c(2,3)],by=list(dd$name),function(x,y) my_t.test2(dd[,3],dd[,2]))

我以为聚合函数只会将与列表中的值匹配的行发送到函数my_t.test2,然后移至下一个列表元素。但是,产生的结果表明它正在对列中的所有值进行t检验,如下所示。然后将所有这些值放入结果中。

t.test(dd[,3],dd[,2])$p.value

我想念什么?这是原始my_test.2的问题,还是如何构造聚合函数的问题,还是其他问题?我应用它的方式似乎并不统一。

这些是我想要的结果。

t.test(c(11,12,13,14),c(3.1,3.2,3.3,3.4))$p.value
t.test(c(3.1,3.2,3.3,3.4),c(3.1,3.2,3.3,3.4))$p.value

注意,这是一个玩具示例,实际数据集将有超过100,000个条目,需要按名称列中的值进行分组。因此,为什么我需要聚合函数。

谢谢您的帮助。

弗里克先生

aggregate不是正确的函数,因为摘要函数一次只能在一个列上使用。使用此方法无法同时获取ab值。

解决该问题的另一种方法是拆分数据,然后将t检验应用于每个子集。这是一个实现

sapply(
    split(dd[-1], dd$names), 
    function(x) t.test(x[["a"]], x[["b"]])$p.value
)

在此,我dd为的每个值划分为一个子集列表namesdd[-1]曾经从子集中删除“名称”列,到只有两列的data.frame。一为ab

然后,t.test使用ab对列表中的每个子集执行一次然后,我提取p值。sapply与计算的包装对于每个子集此p值和细沟返回p值的命名的向量,其中条目的名称对应于水平dd$names

         1st          2nd 
6.727462e-04 3.436403e-05 

如果您想以这种方式进行配对t检验,则可以

sapply(
    split(dd[-1], dd$names), 
    function(x) t.test(x[["a"]] - x[["b"]])$p.value
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章