【问题标题】:Formatting data for a chi square test in RR中卡方检验的格式化数据
【发布时间】:2020-04-12 10:42:04
【问题描述】:

我正在尝试重新格式化我的数据以在 r 中运行卡方检验。我的数据在一列中设置了我的自变量,另外两列中设置了我的自变量组的计数。我在这里做了一个我的数据格式的例子。

> example <- data.frame(category = c("x","y","x","y"), true = c(2,4,6,3), false = c(7,9,3,5))
> example
  category true false
1        x    2     7
2        y    4     9
3        x    6     3
4        y    3     5

据我所知, chisq.test 函数无法处理这种格式的数据,所以我认为我需要重新格式化数据,使其看起来像下面的“好例子”来运行该函数。我的问题是我不确定为大型数据集执行此旋转的简单方法。

> good_example <- data.frame(category = c('x','x','y','y','x','x','y','y'),
                           variable = c('true','false','true','false','true','false','true','false'),
                           count = c(2,7,4,9,6,3,3,5))
> good_example
  category variable count
1        x     true     2
2        x    false     7
3        y     true     4
4        y    false     9
5        x     true     6
6        x    false     3
7        y     true     3
8        y    false     5
> tab <- tapply(good_example$count, list(good_example$category, good_example$variable), FUN=sum)
> chisq.test(tab, correct = FALSE)

    Pearson's Chi-squared test

data:  tab
X-squared = 0.50556, df = 1, p-value = 0.4771

【问题讨论】:

  • tidyr 你可以使用pivot_longer 和类似的东西:pivot_longer(example, cols = c("true", "false"), names_to = "variable", values_to = "count")

标签: r dplyr formatting chi-squared


【解决方案1】:

如果只需要根据x和y总结所有真假,那么:

tab = do.call(rbind,by(example[,-1],example$category,colSums))
chisq.test(tab,correct=FALSE)

一个更紧凑的版本(@markus 指出),您可以根据类别拆分数据,并将 sum 函数应用于除用于拆分的列之外的所有列:

tab = aggregate(.~category, example, sum)

或者也许是 dplyr / tidyr 版本:

library(dplyr)
tab = example %>% group_by(category) %>% summarise_all(sum)
chisq.test(tab[,-1],correct=FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2017-01-03
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多