首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用summarise_all [R]在dplyr组内执行t测试

使用summarise_all [R]在dplyr组内执行t测试
EN

Stack Overflow用户
提问于 2020-05-12 14:18:07
回答 1查看 141关注 0票数 2

假设我想用两种不同的货币来比较每个国家的苹果和橘子的价格:美国和BTC。

每个国家的美国水果

各国的BTC ~水果

代码语言:javascript
复制
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)上使用dplyr::summarise_all函数执行t测试?到目前为止,我尝试过的方法一直给我带来错误。

代码语言:javascript
复制
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') 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-12 14:26:29

你可以通过将数据从宽格式转换为长格式来做这件事。下面是使用dplyr的解决方案:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61754107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档