R:使用t.test函数对多列进行t测试 [英] R: t test over multiple columns using t.test function

查看:905
本文介绍了R:使用t.test函数对多列进行t测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to perform independent t-test for many columns of a dataframe. For example, i created a data frame

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))

To run the test, i used 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 loop 2. apply() 3.也许dplyr

I wonder how can I achieve the results using 1. for loop 2. apply() 3. perhaps dplyr

此链接 R:对所有列进行t检验是相关的,但这确实是6岁.也许有更好的方法来做同样的事情.

This link R: t-test over all columns is related but it was 6 years old. Perhaps there are better ways to do the same thing.

推荐答案

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

Use select_if to select only numeric columns then use purrr:map_df to apply t.test against grp. Finally use broom:tidy to get the results in tidy format

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软件包(v0.2.1.9000)创建于2019-03-15

Created on 2019-03-15 by the reprex package (v0.2.1.9000)

这篇关于R:使用t.test函数对多列进行t测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆