【发布时间】:2012-03-12 03:39:20
【问题描述】:
我尝试对数据框的所有列(一次两列)进行 t 检验,并仅提取 p 值。这是我想出的:
for (i in c(5:525) ) {
t_test_p.value =sapply( Data[5:525], function(x) t.test(Data[,i],x, na.rm=TRUE)$p.value)
}
我的问题是: 1.有没有办法不用循环? 2. 如何捕获t检验的结果。
【问题讨论】:
标签: r
我尝试对数据框的所有列(一次两列)进行 t 检验,并仅提取 p 值。这是我想出的:
for (i in c(5:525) ) {
t_test_p.value =sapply( Data[5:525], function(x) t.test(Data[,i],x, na.rm=TRUE)$p.value)
}
我的问题是: 1.有没有办法不用循环? 2. 如何捕获t检验的结果。
【问题讨论】:
标签: r
我建议将您的数据框转换为长格式并使用pairwise.t.test 和适当的p.adjust:
> library(reshape2)
>
> df <- data.frame(a=runif(100),
+ b=runif(100),
+ c=runif(100)+0.5,
+ d=runif(100)+0.5,
+ e=runif(100)+1,
+ f=runif(100)+1)
>
> d <- melt(df)
Using as id variables
>
> pairwise.t.test(d$value, d$variable, p.adjust = "none")
Pairwise comparisons using t tests with pooled SD
data: d$value and d$variable
a b c d e
b 0.86 - - - -
c <2e-16 <2e-16 - - -
d <2e-16 <2e-16 0.73 - -
e <2e-16 <2e-16 <2e-16 <2e-16 -
f <2e-16 <2e-16 <2e-16 <2e-16 0.63
P value adjustment method: none
> pairwise.t.test(d$value, d$variable, p.adjust = "bon")
Pairwise comparisons using t tests with pooled SD
data: d$value and d$variable
a b c d e
b 1 - - - -
c <2e-16 <2e-16 - - -
d <2e-16 <2e-16 1 - -
e <2e-16 <2e-16 <2e-16 <2e-16 -
f <2e-16 <2e-16 <2e-16 <2e-16 1
P value adjustment method: bonferroni
【讨论】:
试试这个
X <- rnorm(n=50, mean = 10, sd = 5)
Y <- rnorm(n=50, mean = 15, sd = 6)
Z <- rnorm(n=50, mean = 20, sd = 5)
Data <- data.frame(X, Y, Z)
library(plyr)
combos <- combn(ncol(Data),2)
adply(combos, 2, function(x) {
test <- t.test(Data[, x[1]], Data[, x[2]])
out <- data.frame("var1" = colnames(Data)[x[1]]
, "var2" = colnames(Data[x[2]])
, "t.value" = sprintf("%.3f", test$statistic)
, "df"= test$parameter
, "p.value" = sprintf("%.3f", test$p.value)
)
return(out)
})
X1 var1 var2 t.value df p.value
1 1 X Y -5.598 92.74744 0.000
2 2 X Z -9.361 90.12561 0.000
3 3 Y Z -3.601 97.62511 0.000
【讨论】:
这是另一个解决方案,outer。
outer(
1:ncol(Data), 1:ncol(Data),
Vectorize(
function (i,j) t.test(Data[,i], Data[,j])$p.value
)
)
【讨论】:
假设您的数据框如下所示:
df = data.frame(a=runif(100),
b=runif(100),
c=runif(100),
d=runif(100),
e=runif(100),
f=runif(100))
以下
tests = lapply(seq(1,length(df),by=2),function(x){t.test(df[,x],df[,x+1])})
将为您提供每组列的测试。请注意,这只会为您提供 a & b、c & d 和 e & f 的 t.test。 如果你想要 a&b、b&c、c&d、d&e 和 e&f,那么你必须这样做:
tests = lapply(seq(1,(length(df)-1)),function(x){t.test(df[,x],df[,x+1])})
最后,假设您只想要测试中的 P 值,那么您可以这样做:
pvals = sapply(tests, function(x){x$p.value})
如果您不确定如何使用对象,请尝试输入 summary(tests) 和 str(tests[[1]]) - 在这种情况下 test 是 htest 对象的列表,并且您想知道htest 对象的结构,不一定是列表。
希望这有帮助!
【讨论】:
我运行这个:
tres<-apply(x,1,t.test)
pval<-vapply(tres, "[[", 0, i = "p.value")
我花了一段时间来猜想将 pval 从 t.test 结果对象列表中拉出的“vapply”技巧。 (由于 Henrik 在下面的评论,我从 'sapply' 编辑了这个)
如果是配对 t 检验,您只需减去并检验 mean=0,得出完全相同的结果(这就是配对 t.test 的全部内容):
tres<-apply(y-x,1,t.test)
pval<-vapply(tres, "[[", 0, i = "p.value")
这又是对所有列的每行 t 检验。
【讨论】:
sapply,使用vapply。你不需要unlist,如果数据不符合预期,它会出错。此外,您还可以使用"[["。所以我会这样做:vapply(tres, "[[", 0, i = "p.value")(0 只是表示应该返回一个数字)