两个数据帧之间的 T 测试并按 R 中的相似行分组

T test between two dataframes and grouped by similar rows in R

标题可能不是很清楚,但希望我能在这里更好地描述它。我有两个数据框,每个数据框都描述了不同类型客户的每月支出。例如,对于 A 客户,我有一个像

这样的数据框
year_month    customer_id     monthly_spending
201301        123             5.50
201301        124             2.30
201301        125             6.80
201302        123             8.30
201302        124             5.60

那我也有一个类似的dataframe给B客户。理想情况下,我想要一个数据框,其中我有每个月的 T 测试结果,比较 A 客户和 B 客户之间的支出。如果所有数据都在一个数据帧中,我可以使用 dplyr() 和 Broom() 来做到这一点。如果我有两个数据帧,有没有办法做到这一点,或者最好将两者合并在一起然后进行 T 检验和 group_by year_month?

我同意@Gainz 在概念上的评论。组合数据帧可能是最简单的方法。但是,真正的 merge-type 操作,例如left_join() 等可能实际上并不需要;只需使用 bind_rows() 就足够了。

# read data from question
df_A <-
'year_month    customer_id     monthly_spending
201301        123             5.50
201301        124             2.30
201301        125             6.80
201302        123             8.30
201302        124             5.60' %>% 
    str_replace_all('[ ]++', '\t') %>% 
    read_tsv

# simulate more data for customer group "B"
df_B <- 
    df_A %>%    
    mutate(monthly_spending = monthly_spending + rnorm(5))

# combine the dataframes
df_all <-
    bind_rows(list('A' = df_A, 'B' = df_B), .id = 'customer_type')

# use broom to do a tidy t.test()
df_all %>% 
    group_by(year_month) %>%
    do(tidy(t.test(formula = monthly_spending ~ customer_type, 
                   data=.)))

这里的组合数据框df_all

# A tibble: 10 x 4
   customer_type year_month customer_id monthly_spending
   <chr>              <dbl>       <dbl>            <dbl>
 1 A                 201301         123             5.5 
 2 A                 201301         124             2.3 
 3 A                 201301         125             6.8 
 4 A                 201302         123             8.3 
 5 A                 201302         124             5.6 
 6 B                 201301         123             6.25
 7 B                 201301         124             2.63
 8 B                 201301         125             7.04
 9 B                 201302         123             9.11
10 B                 201302         124             5.11

执行 t.tests 的结果是

# A tibble: 2 x 11
# Groups:   year_month [2]
  year_month estimate estimate1 estimate2 statistic p.value parameter conf.low
       <dbl>    <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>
1     201301  -0.692       4.87      5.56   -0.341    0.750      3.93    -6.35
2     201302  -0.0453      6.95      7.00   -0.0334   0.979      1.02   -16.4 
# … with 3 more variables: conf.high <dbl>, method <chr>, alternative <chr>