gpt4 book ai didi

r - R:使用t.test函数对多列进行t测试

转载 作者:行者123 更新时间:2023-12-05 00:48:46 36 4
gpt4 key购买 nike

我试图对数据框的许多列执行独立的t检验。例如,我创建了一个数据框

set seed(333)
a <- rnorm(20, 10, 1)
b <- rnorm(20, 15, 2)
c <- rnorm(20, 20, 3)
grp <- rep(c('m', 'y'),10)
test_data <- data.frame(a, b, c, grp)

为了运行测试,我使用了 with(df, t.test(y ~ group))
with(test_data, t.test(a ~ grp))
with(test_data, t.test(b ~ grp))
with(test_data, t.test(c ~ grp))

我想要这样的输出
mean in group m mean in group y  p-value
9.747412 9.878820 0.6944
15.12936 16.49533 0.07798
20.39531 20.20168 0.9027

我想知道如何使用
1. for loop2. apply()3.也许 dplyr
这个链接 R: t-test over all columns是相关的,但是它已经有6年的历史了。也许有更好的方法来做同样的事情。

最佳答案

使用select_if仅选择数字列,然后使用purrr:map_dft.test应用于grp。最后使用broom:tidy以整齐的格式获取结果

library(tidyverse)

res <- test_data %>%
select_if(is.numeric) %>%
map_df(~ broom::tidy(t.test(. ~ grp)), .id = 'var')
res
#> # A tibble: 3 x 11
#> var estimate estimate1 estimate2 statistic p.value parameter conf.low
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 a -0.259 9.78 10.0 -0.587 0.565 16.2 -1.19
#> 2 b 0.154 15.0 14.8 0.169 0.868 15.4 -1.78
#> 3 c -0.359 20.4 20.7 -0.287 0.778 16.5 -3.00
#> # ... with 3 more variables: conf.high <dbl>, method <chr>,
#> # alternative <chr>

reprex package(v0.2.1.9000)创建于2019-03-15

关于r - R:使用t.test函数对多列进行t测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48907955/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com