I have ran 3 chi suqared tests and I have combined them using the code below.
df2 <- data.frame(chisq.test_age, chisq.test_eth, chisq.test_reg, chisq.test_sex)
I have attached a photo below of what happens. Is there a way I can have this so the results are not just in a straight line? i.e where I have the variables on the y axis and the results (e.g p value) on the x axis.
CodePudding user response:
You could use broom's tidy
and dplyr's bind_rows
:
library(tidyverse)
library(broom)
chit1 <- chisq.test(xtabs(Freq ~ Sex Class, data = as.data.frame(Titanic)))
chit2 <- chisq.test(xtabs(mpg ~ disp hp, data = as.data.frame(mtcars)))
bind_rows(
tidy(chit1),
tidy(chit2)
)
#> # A tibble: 2 × 4
#> statistic p.value parameter method
#> <dbl> <dbl> <int> <chr>
#> 1 350. 1.56e-75 3 Pearson's Chi-squared test
#> 2 13222. 0 546 Pearson's Chi-squared test
Created on 2022-05-12 by the reprex package (v2.0.1)
CodePudding user response:
Here is a base R way. The tests' results are put in a list with mget/ls
, then a series of lapply
loops gets the relevant list members. Finally, do.call
bind them together.
The tests are taken from help("chisq.test")
.
# 1st test
M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("F", "M"),
party = c("Democrat","Independent", "Republican"))
chisq.test_Xsq1 <- chisq.test(M)
# 2nd test
x <- matrix(c(12, 5, 7, 7), ncol = 2)
chisq.test_Xsq2 <- chisq.test(x)
# 3rd test
x <- c(A = 20, B = 15, C = 25)
chisq.test_Xsq3 <- chisq.test(x)
test_list <- mget(ls(pattern = "^chisq.test_"))
test_list <- lapply(test_list, unclass)
test_list <- lapply(test_list, `[`, 1:3)
do.call(rbind, test_list)
#> statistic parameter p.value
#> chisq.test_Xsq1 30.07015 2 2.953589e-07
#> chisq.test_Xsq2 0.6411203 1 0.4233054
#> chisq.test_Xsq3 2.5 2 0.2865048
Created on 2022-05-12 by the reprex package (v2.0.1)