r - 使用 summarise_all [R] 在 dplyr 组内执行 t 检验

标签 r dplyr tidyr

假设我想比较每个国家/地区以两种不同货币(美国和比特币)计算的苹果和橙子的价格。

美国〜每个国家的水果
BTC ~ 每个国家的水果

library(tidyverse)

prices <- tibble(
  country = c(rep("USA", 6), rep("Spain", 6), rep("Korea", 6)),
  fruit = rep(c("apples", "apples", "apples", "oranges", "oranges", "oranges"), 3),
  price_USA = rnorm(18),
  price_BTC = rnorm(18)
)

prices %>% 
  group_by(country) %>% 
  summarise(
    pval_USA = t.test(price_USA ~ fruit)$p.value
    pval_BTC = t.test(price_BTC ~ fruit)$p.value
  )

现在假设有很多列,我想使用 summarise_all 而不是命名每个列。有没有办法使用 在每个组(country)和每列(price_USAprice_BTC)上执行 t 检验>dplyr::summarise_all 函数?到目前为止我尝试过的方法一直给我带来错误。

prices %>% 
  group_by(country) %>% 
  summarise_at(
    c("price_USA", "price_BTC"),
    function(x) {t.test(x ~ .$fruit)$p.value}
  )
> Error in model.frame.default(formula = x ~ .$fruit) : 
  variable lengths differ (found for '.$fruit') 

最佳答案

您可以通过reshaping your data from wide to long format来做到这一点。这是使用 dplyr 的解决方案:

library(tidyverse)

prices <- tibble(
  country = c(rep("USA", 6), rep("Spain", 6), rep("Korea", 6)),
  fruit = rep(c("apples", "apples", "apples", "oranges", "oranges", "oranges"), 3),
  price_USA = rnorm(18),
  price_BTC = rnorm(18)
)

prices %>% 
  pivot_longer(cols = starts_with("price"), names_to = "name",
               values_to = "price", names_prefix = "price_") %>%
  group_by(country, name) %>%
  summarise(pval = t.test(price ~ fruit)$p.value)
#> # A tibble: 6 x 3
#> # Groups:   country [3]
#>   country name   pval
#>   <chr>   <chr> <dbl>
#> 1 Korea   BTC   0.458
#> 2 Korea   USA   0.721
#> 3 Spain   BTC   0.732
#> 4 Spain   USA   0.526
#> 5 USA     BTC   0.916
#> 6 USA     USA   0.679

关于r - 使用 summarise_all [R] 在 dplyr 组内执行 t 检验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61754107/

相关文章:

r - 使用标准评估和 do_ 在参数网格上运行模拟,无需 do.call

r - 使用与列名同名的全局变量过滤数据框

r - 使用 openrouteservice-r 为位置数据帧创建多个等时线

r - 计算不同组固定年份的百分比变化

r - 如何在向量集上展开.grid 而不是单个元素

c++ - Rcpp 在不打印空行时产生不同的输出

r - R 网络图中的顶点框架宽度

R:加快将巨大的 data.frame 写入文本文件的速度?

r - 在行之间累积添加数字以在 R 中创建新列

R:在单个因子变量上加宽多个列