与同一列上的第一组进行分组和成对假设检验

问题描述 投票:1回答:1

假设我有mtcars数据集,其列为mpgcyl

mpg cyl
21.0   6
21.0   6
22.8   4
21.4   6
18.7   8
18.1   6

我想计算其中t.test()与其他组之间的所有wilcox.test()(或cyl == 4)统计信息。结果应该是类似以下内容的小标题:

mpg_4 <- mtcars %>% filter(cyl == 4) %>% select(mpg)
mpg_6 <- mtcars %>% filter(cyl == 6) %>% select(mpg)
mpg_8 <- mtcars %>% filter(cyl == 8) %>% select(mpg)

bind_rows(
  broom::tidy(t.test(mpg_4, mpg_4)), 
  broom::tidy(t.test(mpg_4, mpg_6)), 
  broom::tidy(t.test(mpg_4, mpg_)
  )

除非有更清洁的方法,否则我想使用purrrbroom来执行此操作。请注意,它应适用于n个组,并且应适用于轻松更改为其他测试。

r dplyr purrr broom
1个回答
1
投票

首先,我们将每个mpgcyl值向量隔离到它们自己的列表元素中:

X <- mtcars %>% group_by(cyl) %>% summarize_at("mpg", list) %>% deframe
# $`4`
#  [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4

# $`6`
# [1] 21.0 21.0 21.4 18.1 19.2 17.8 19.7

# $`8`
#  [1] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 13.3 19.2 15.8 15.0

然后我们针对列表中的每个元素计算第一个元素的t.test并将结果合并到一个数据框中:

map( X, t.test, X[["4"]] ) %>% map( broom::tidy ) %>% bind_rows( .id = "cyl" )
# # A tibble: 3 x 11
#   cyl   estimate estimate1 estimate2 statistic    p.value parameter conf.low conf.high method                  alternative
#   <chr>    <dbl>     <dbl>     <dbl>     <dbl>      <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>      
# 1 4         0         26.7      26.7      0    1               20      -4.01      4.01 Welch Two Sample t-test two.sided  
# 2 6        -6.92      19.7      26.7     -4.72 0.000405        13.0   -10.1      -3.75 Welch Two Sample t-test two.sided  
# 3 8       -11.6       15.1      26.7     -7.60 0.00000164      15.0   -14.8      -8.32 Welch Two Sample t-test two.sided  
© www.soinside.com 2019 - 2024. All rights reserved.