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

KIM*_*KIM 6 loops r apply

我尝试对数据帧的许多列执行独立的 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)
Run Code Online (Sandbox Code Playgroud)

为了运行测试,我使用了 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))
Run Code Online (Sandbox Code Playgroud)

我想要这样的输出

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
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用 1. for loop 2. apply() 3.来实现结果。也许dplyr

这个链接R: t-test over all columns是相关的,但它已经有 6 年的历史了。也许有更好的方法来做同样的事情。

Tun*_*ung 7

用于select_if仅选择数字列,然后purrr:map_df用于t.testgrp. 最后用于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>
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.1.9000)于 2019 年 3 月 15 日创建