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

Viewed 42

For example I have a dataset

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

I am able to run each row individually and get the information i want for example

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

but i would like to run it in a loop and not have to repeat the same line of code 4 times.My goal is for something like this.

 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

Made an attempt like this

library(broom)

Results<-for (i in 1:nrow(df)) {
assign(tidy(chisq.test(matrix(unlist(df[1,]), ncol  = 2))))
}

Credit to: akrun for previous help

1 Answers

An option is apply with MARGIN = 1 to loop over the rows. Within each row, it is a vector, so we just need to wrap with matrix to convert to a matrix with specified dimensions, apply the chisq.test and get the output in a tibble format with tidy

library(broom)
library(dplyr)
apply(df, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2)))) %>%
     bind_rows

Or this can be done in tidyverse with pmap

library(purrr)
pmap_dfr(df, ~ c(...) %>%
             matrix(ncol = 2) %>%
             chisq.test %>%
             tidy)

-output

# 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
Related