首页 > 解决方案 > 通过运行 chisq.test 或任何其他统计格式,我如何将结果提取到数据框中?

问题描述

我有一个两个两个

structure(list(BLACK = c(138L, 29L), WHITE = c(6L, 0L)), row.names = c("YES RS", 
"NO RS"), class = "data.frame")

然后我跑

chisq.test(answer[ , c("BLACK", "WHITE")])

我看到我得到了结果,但是当我这样做时

as.data.frame(chisq.test(answer[ , c("BLACK", "WHITE")]))

它给了我一个错误信息。有没有一种简单的方法来获取所有结果,如 p 值,或任何其他信息作为列以及它们在行中的相应信息?

标签: rdataframe

解决方案


如果我们检查str输出的结构chisq.test,它是一个list不同的元素,lengthclass其中一些是matrix,一些是vector等等。

out <- chisq.test(answer[ , c("BLACK", "WHITE")])
str(out)
List of 9
 $ statistic: Named num 0.317
  ..- attr(*, "names")= chr "X-squared"
 $ parameter: Named int 1
  ..- attr(*, "names")= chr "df"
 $ p.value  : num 0.574
 $ method   : chr "Pearson's Chi-squared test with Yates' continuity correction"
 $ data.name: chr "answer[, c(\"BLACK\", \"WHITE\")]"
 $ observed : int [1:2, 1:2] 138 29 6 0
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "YES RS" "NO RS"
  .. ..$ : chr [1:2] "BLACK" "WHITE"
 $ expected : num [1:2, 1:2] 139.01 27.99 4.99 1.01
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "YES RS" "NO RS"
  .. ..$ : chr [1:2] "BLACK" "WHITE"
 $ residuals: num [1:2, 1:2] -0.0853 0.1901 0.4501 -1.0029
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "YES RS" "NO RS"
  .. ..$ : chr [1:2] "BLACK" "WHITE"
 $ stdres   : num [1:2, 1:2] -1.12 1.12 1.12 -1.12
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:2] "YES RS" "NO RS"
  .. ..$ : chr [1:2] "BLACK" "WHITE"
 - attr(*, "class")= chr "htest"

一种转换为的方法data.frame是提取那些vector具有相同长度的元素,即

as.data.frame(out[1:3])

因为data.frame只是一个list具有一些附加属性及其相同的列/元素length


或者使用从输出tidy中返回tibble 带有一些元素的方法

library(broom)
tidy(out)
# A tibble: 1 x 4
# statistic p.value parameter method                                                      
#     <dbl>   <dbl>     <int> <chr>                                                       
#1     0.317   0.574         1 Pearson's Chi-squared test with Yates' continuity correction

推荐阅读