对DataFrame中一列的所有组组合进行T检验 [英] T-Test on all group combinations of one column inside DataFrame
本文介绍了对DataFrame中一列的所有组组合进行T检验的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想进行t检验并提取分组因子所有组合的p值.数据框只有2列.虚拟数据示例:
I want to run t-tests and extract the p-values for all combinations of a grouping factor. The dataframe only has 2 columns. Dummy data example:
set.seed(123)
df <- data.frame(
Group = c(rep("A", 5), rep("B", 4), rep("C", 6)),
Val = c(sample(101:200, 5, replace = T), sample(1:100, 4, replace = T), sample(1:100, 6, replace = T))
)
所需的输出
data.frame(
A = c(1, 0.00191, 0.00017),
B = c(0.00191,1,0.88500),
C = c(0.00017,0.88500,1)
)
A B C
1 1.00000 0.00191 0.00016
2 0.00191 1.00000 0.88500
3 0.00016 0.88500 1.00000
为方便起见,这是 t.test
的包装函数,用于提取pvalue
For convenience, here's a wrapper function for t.test
that extracts the pvalue
tWrap <- function(x, y) t.test(x, y)$p.value
谢谢,我已经在网上搜索了使用 group_by
和 purrr :: map
的解决方案,但无法破解.
Thank you, I've scoured the web for solutions using group_by
and purrr::map
but can't crack it.
推荐答案
Base R解决方案
Base R solution
我修改了 tWrap
tWrap <- function(x) t.test(x$Var1, x$Var2)$p.value
L <- split(df$Val, df$Group)
pvals <- apply(expand.grid(L, L), 1, tWrap)
pvals_mat <- matrix(pvals, ncol=3)
# [,1] [,2] [,3]
# [1,] 1.0000000000 0.001918324 0.0001655259
# [2,] 0.0019183244 1.000000000 0.8850039246
# [3,] 0.0001655259 0.885003925 1.0000000000
这篇关于对DataFrame中一列的所有组组合进行T检验的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文