我有一个数据集,如下所示:
id samediff factor value
1 S give 3
1 S impact 4
2 S give 2
2 S impact 5
3 D give 1
3 D impact 4
4 D give 3
4 D impact 5 我想执行几个t.tests来比较S (samediff)条件下每个因子的平均值与D (samediff)条件下相同因子的平均值。
我知道我可以这样做:
dfgive<-filter(df, factor == "give")
t.test(value~samediff, dfgive)
dfimpact<-filter(df, factor == "impact")
t.test(value~samediff, dfimpact) 有没有一种方法可以在较少的行中执行多个t.tests?在实际的数据集中,有几个因素比这里包含的因素更多。我希望能够执行所有必要的t.tests,而不需要按照前面所示的方式创建单独的数据格式。
发布于 2018-06-28 03:41:58
我们可以根据“因子”和summarise ( t.test在list中的输出)进行分组
library(dplyr)
out <- df %>%
group_by(factor) %>%
summarise(ttest = list(t.test(value ~ samediff)))
out
# A tibble: 2 x 2
# factor ttest
# <chr> <list>
#1 give <S3: htest>
#2 impact <S3: htest>输出存储在list列中,该列可以用$或[[提取。
identical(out$ttest[[1]], t.test(value ~ samediff, dfgive))
#[1] TRUE发布于 2018-06-28 03:56:11
为了增加现有的答案,您可以使用broom::tidy来整理来自t.test的输出。
library(tidyverse)
library(broom)
df %>%
group_by(factor) %>%
summarise(ttest = list(t.test(value ~ samediff))) %>%
mutate(ttest = map(ttest, tidy)) %>%
unnest() %>%
select(factor, estimate, estimate1, estimate2, p.value)
# # A tibble: 2 x 5
# factor estimate estimate1 estimate2 p.value
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 give -0.5 2 2.5 0.712
# 2 impact 0 4.5 4.5 1 下面是一个基本-R方法:
results <- lapply(split(df, df$factor), function(X) {
out <- t.test(value ~ samediff, X)
data.frame(diff = out$statistic,
mean1 = out$estimate[1],
mean2 = out$estimate[2],
pval = out$p.value)
})
do.call(rbind, results)
# diff mean1 mean2 pval
# give -0.4472136 2.0 2.5 0.7117228
# impact 0.0000000 4.5 4.5 1.0000000发布于 2018-06-28 03:48:02
我们可以通过factor对数据进行拆分,然后逐个应用t.test。最后的输出是一个列表。我们可以通过lst$give或lst$impact访问结果。
library(tidyverse)
lst <- df %>%
split(.$factor) %>%
map(~t.test(value ~ samediff, .x))数据
df <- read.table(text = "id samediff factor value
1 S give 3
1 S impact 4
2 S give 2
2 S impact 5
3 D give 1
3 D impact 4
4 D give 3
4 D impact 5 ",
header = TRUE, stringsAsFactors = FALSE)https://stackoverflow.com/questions/51074328
复制相似问题