如何解决使用 R,我想遍历每一行并为每一行创建相应的卡方结果
例如我有一个数据集
structure(list(`total primary - yes RS` = c(138L,101L,86L,118L),`total primary - no RS` = c(29L,39L,35L,38L),`total secondary- yes rs` = c(6L,15L,3L,15L),`total secondary- no rs` = c(0L,7L,1L,2L)),row.names = c(NA,-4L),class = c("tbl_df","tbl","data.frame"))
我能够单独运行每一行并获取我想要的信息
Result<-tidy(chisq.test(matrix(unlist(df[1,]),ncol = 2)))
Result2<-tidy(chisq.test(matrix(unlist(df[2,ncol = 2)))
Result3<-tidy(chisq.test(matrix(unlist(df[3,ncol = 2)))
Result4<-tidy(chisq.test(matrix(unlist(df[4,ncol = 2)))
但我想在循环中运行它,而不必重复同一行代码 4 次。我的目标是这样的。
statistic|p.value|parameter|method
0.3165439 0.5736921 1 Pearson's Chi-squared test with Yates' continuity correction
0.01656976 0.8975764 1 Pearson's Chi-squared test with Yates' continuity correction
6.698956e-32 1 1 Pearson's Chi-squared test with Yates' continuity correction
0.7511235 0.3861208 1 Pearson's Chi-squared test with Yates' continuity correction
尝试过这样的
library(broom)
Results<-for (i in 1:nrow(df)) {
assign(tidy(chisq.test(matrix(unlist(df[1,ncol = 2))))
}
感谢:akrun 以前的帮助
解决方法
一个选项是 apply
和 MARGIN = 1
来循环遍历行。在每一行中,它是一个 vector
,因此我们只需要用 matrix
包裹以转换为具有指定 matrix
张力的 dim
,应用 chisq.test
并使用 tidy
library(broom)
library(dplyr)
apply(df,1,function(x) tidy(chisq.test(matrix(x,ncol = 2)))) %>%
bind_rows
或者这可以在 tidyverse
中使用 pmap
library(purrr)
pmap_dfr(df,~ c(...) %>%
matrix(ncol = 2) %>%
chisq.test %>%
tidy)
-输出
# A tibble: 4 x 4
# statistic p.value parameter method
# <dbl> <dbl> <int> <chr>
#1 3.17e- 1 0.574 1 Pearson's Chi-squared test with Yates' continuity correction
#2 1.66e- 2 0.898 1 Pearson's Chi-squared test with Yates' continuity correction
#3 6.70e-32 1.00 1 Pearson's Chi-squared test with Yates' continuity correction
#4 7.51e- 1 0.386 1 Pearson's Chi-squared test with Yates' continuity correction
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。