I would like to create contingency tables and run chisq.test() etc. for multiple items in a dataframe.
Various attempts have resulted in 'Error in table(y$x, y$q2) : all arguments must have the same length'.
I think the example below focuses on my central problem, though ultimately I'd write a more complex function. I'd be interested in solutions to my specific function or to my overall approach. Thanks!
my_df <- structure(list(q1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
.Label = c("Choice1", "Choice2"),
class = "factor"),
q2 = structure(c(1L, 1L, 4L, 5L, 4L, 1L, 1L, 4L),
.Label = c("Agree", "Disagree","N/A or No Opinion",
"Strongly Agree", "Strongly Disagree"),
class = "factor"),
q3 = structure(c(1L, 4L, 1L, 4L, 1L, 4L, 4L, 4L),
.Label = c("Agree", "Disagree","N/A or No Opinion",
"Strongly Agree", "Strongly Disagree"),
class = "factor")),
row.names = c(NA, -8L),
class = c("tbl_df", "tbl", "data.frame"))
my_fn <- function(x, y) {
table(y$x, y$`q2`)
}
my_fn(names(my_df)[1], my_df)
#Error in table(y$x, y$q2) : all arguments must have the same length
lapply(names(my_df), my_fn, my_df)
#Error in table(y$x, y$q2) : all arguments must have the same length