使用 R,我想遍历每一行并为每一行创建相应的卡方结果

With R, I would like to loop through each row and create corresponding chisquare results for each row

例如我有一个数据集

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 times.My 目标是这样的。

 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))))
}

感谢:ak运行 以前的帮助

一个选项是 applyMARGIN = 1 来遍历行。在每一行中,它是一个 vector,所以我们只需要用 matrix 换行以转换为具有指定 dimmatrix,应用 chisq.test并使用 tidy

获得 tibble 格式的输出
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