r语言 - 通过运行 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 值或任何其他信息)作为一列及其在行中的相应信息获取?

如果我们检查chisq.test输出的str,它是lengthclass不同的元素的list,即其中一些是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只是一个具有一些附加属性及其相同length列/元素的list


或者使用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

最新更新