gpt4 book ai didi

r - 在汇总的 tibble 中保留 chisq.test 的多个值

转载 作者:行者123 更新时间:2023-12-01 11:14:28 27 4
gpt4 key购买 nike

我对正在执行卡方检验的数据进行了分组,并希望返回一个汇总表,其中包含来自 htest 对象的多个值。例如 ( from a previous question ),

library(dplyr)

set.seed(1)
foo <- data.frame(
partido=sample(c("PRI", "PAN"), 100, 0.6),
genero=sample(c("H", "M"), 100, 0.7),
GM=sample(c("Bajo", "Muy bajo"), 100, 0.8)
)

foo %>%
group_by(GM) %>%
summarise(p.value=chisq.test(partido, genero)$p.value))

返回 p 值,但我想从 htest 对象中获取多个值(比如 p.valuestatistic)作为汇总表中的不同列返回。

我试过了

foo %>%
group_by(GM) %>%
summarise(htest=chisq.test(partido, genero)) %>%
mutate(p.value=htest$p.value, statistic=htest$statistic)

但这会引发错误

Error in summarise_impl(.data, dots) :
Column htest must be length 1 (a summary value), not 9

您如何使用 tidyverse 工具完成此任务?

最佳答案

另一种选择是利用 broom::tidy

library(broom)
library(tidyverse)
foo %>%
group_by(GM) %>%
nest() %>%
transmute(
GM,
res = map(data, ~tidy(chisq.test(.x$partido, .x$genero)))) %>%
unnest()
## A tibble: 2 x 5
# GM statistic p.value parameter method
# <fct> <dbl> <dbl> <int> <chr>
#1 Bajo 0.0157 0.900 1 Pearson's Chi-squared test with Yates' c…
#2 Muy ba… 0.504 0.478 1 Pearson's Chi-squared test with Yates' c…

关于r - 在汇总的 tibble 中保留 chisq.test 的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489669/

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