For loop utilizing colnames as object in tabyl pipeline

Viewed 108

I need to run chi-squared tests on multiple contingency tables and store them into a data frame. I had thought to use the tabyl and chisq.test functions. My original dataset consists of patient symptom reports. A made up example:

Data

df <- structure(list(Race = c("White", "Asian", "White", "Asian", "Black", 
"Asian", "Black", "White"), Headache = c("No", "No", "Yes", "Yes", "No", 
"No", "Yes", "Yes"), Paraesthesias = c("No", "Yes", "Yes", "Yes", "Yes", "No", "No", "No"
), Heartburn = c("Yes", "No", "No", "Yes", "No", "Yes", "Yes", "Yes")), row.names = c(NA, 
-8L), class = "data.frame")

print(df)

Desired outcome via brute force

headache_p <- chisq.test(df[c(1,2)] %>% tabyl(Race, Headache))$p.value

paraesthesias_p <- chisq.test(df[c(1,3)] %>% tabyl(Race, Paraesthesias))$p.value

heartburn_p <- chisq.test(df[c(1,4)] %>% tabyl(Race, Heartburn))$p.value

data.frame("Headache" = headache_p, "Paraesthesias" = paraesthesias_p, "Heartburn" = heartburn_p, row.names = "p.value")

Attempt at getting desired outcome using loop

y <- list()

for (i in 2:4) {
    z <- chisq.test(df[c(1, i)] %>% tabyl(Race, colnames(df[i]), show_na = FALSE))
    y <- c(y, z)
}

setNames(data.frame(y, row.names = "p.value"), colnames(df)[-1])

Error message

Error: Can't extract columns that don't exist.
x Column `Headache` doesn't exist.
Run `rlang::last_error()` to see where the error occurred.

Question

How do I create a for loop for this process? My original data set has 60+ symptoms so a loop would be desired. I do not know how to put column names into the pipeline as it treats it as a character instead of an object.

1 Answers

You can use map_dbl here which would do the job of for loop.

You can use .data argument in tabyl when you pass column names as characters.

library(purrr)
library(dplyr)
library(janitor)

cols <- names(df[-1])

map_dbl(cols, ~chisq.test(df %>% tabyl(Race, .data[[.x]]))$p.value) %>%
  t %>%
  as.data.frame() %>%
  setNames(cols)

#   Headache Paraesthesias Heartburn
#1 0.7165313     0.7165313 0.9149472
Related