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 值,或任何其他信息作为列以及它们在行中的相应信息?
解决方案
如果我们检查str
输出的结构chisq.test
,它是一个list
不同的元素,length
即class
其中一些是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
推荐阅读
- python - Python中的动态数据框转换
- ant - Apache ANT:get 不支持嵌套的“header”元素
- excel - 无效的过程调用或参数 excel - for 循环中的错误 5
- python - 从具有最多数据(非 NA)的三列创建组合列
- node.js - 使用 nodejs 获取 DNS 后缀
- python - 类中的意外缩进错误 __init__
- java - 如何在 MongoDB 中将 DateTime 转换为 Date 以进行过滤?
- grpc - grpc java中ListenableFuture风格的存根和异步存根之间的区别
- python - Wagtail CMS Draftail 内联元素和类未显示
- wordpress - Wordpress,register_taxonomy 的 default_term 参数,复选框未在视觉上检查