这个问题与此相关跨多列进行 T 检验或整理数据 https://stackoverflow.com/questions/69951627/t-tests-across-multiple-columns-or-tidy-the-data#69951627.
data:
df <- structure(list(Subject = 1:3, PreScoreTestA = c(30L, 15L, 20L
), PostScoreTestA = c(40L, 12L, 22L), PreScoreTestB = c(6L, 9L,
11L), PostScoreTestB = c(8L, 13L, 12L), PreScoreTestC = c(12L,
7L, 9L), PostScoreTestC = c(10L, 7L, 10L)), class = "data.frame", row.names = c(NA,
-3L))
> df
Subject PreScoreTestA PostScoreTestA PreScoreTestB PostScoreTestB PreScoreTestC PostScoreTestC
1 1 30 40 6 8 12 10
2 2 15 12 9 13 7 7
3 3 20 22 11 12 9 10
这里OP询问是否可以申请t.test
到成对的列宽格式数据框。已经提供了使用长格式的解决方案。
不过,我尝试应用以下代码作为以宽格式执行 t.test 的答案。
我的代码使用+
作为函数(效果很好):
library(dplyr)
library(stringr)
df %>%
mutate(across(starts_with('PreScore'), ~ . +
get(str_replace(cur_column(), "^PreScore", "PostScore")), .names = "{.col}_TTest")) %>%
rename_at(vars(ends_with('TTest')), ~ str_remove(., "PreScore"))
# gives:
Subject PreScoreTestA PostScoreTestA PreScoreTestB PostScoreTestB PreScoreTestC PostScoreTestC
1 1 30 40 6 8 12 10
2 2 15 12 9 13 7 7
3 3 20 22 11 12 9 10
TestA_TTest TestB_TTest TestC_TTest
1 70 14 22
2 27 22 14
3 42 23 19
现在我想改变功能+
by t.test
(这不起作用,我尝试了很多变体):
library(dplyr)
library(stringr)
df %>%
mutate(across(starts_with('PreScore'), ~ . t.test
get(str_replace(cur_column(), "^PreScore", "PostScore")), .names = "{.col}_TTest")) %>%
rename_at(vars(ends_with('TTest')), ~ str_remove(., "PreScore"))
我想知道:
是否可以申请t.test
函数到预定义列对的集合across
就像有可能-
+
/
etc...
我已经通过的更多资源:
使用 dplyr 在 R 中循环获取 t.test 结果 https://stackoverflow.com/questions/67596633/looping-to-get-t-test-result-in-r-using-dplyr
dplyr 使用 t.test 总结多列 https://stackoverflow.com/questions/26244321/dplyr-summarise-multiple-columns-using-t-test
对 data.frame 的每对连续列应用 t.test https://stackoverflow.com/questions/40174244/apply-t-test-on-every-consecutive-pair-of-columns-of-a-data-frame
R:使用 t.test 函数对多列进行 t 测试 https://stackoverflow.com/questions/48907955/r-t-test-over-multiple-columns-using-t-test-function