gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:02:37 26 4
gpt4 key购买 nike

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

美国 ~ 每个国家的水果
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_USA )和每列( price_BTCdplyr::summarise_all )内执行 t 检验?功能?到目前为止我尝试过的方法一直给我错误。
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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com