Reputation: 1
The main exposure variable is aff
. I want to get contingency tables for aff
and all variables in the varlist
. Then I want to do chi-square test using these contingency tables. My codes are following:
name=names(data)
varlist=name[11:40]
models=lapply(varlist, function(x) {
chisq.test(table(substitute(data$i,list(i = as.name(x))),data$aff))
})
lapply(models, summary)
But I got error
Error in unique.default(x, nmax = nmax) :
unique() applies only to vectors
How to fix this?
Upvotes: 0
Views: 691
Reputation: 3619
Supposing your data is like mtcars
, where vs
, am
, gear
, and carb
are categorical variables, you can create a function like so:
df_list_f <- function(x) chisq.test(table(df2$cyl, x))
df2 <- mtcars[,8:11] # df2 contains the columns vs, am, gear and carb
lapply(df2, df_list_f)
Upvotes: 0
Reputation: 160447
I think you're over-complicating things by using substitute
and such. Without your data, I'll try with mtcars
, using cyl
as the exposure variable.
data <- mtcars
name <- names(data)
ev <- "cyl"
varlist <- name[ name != ev ]
models <- lapply(varlist, function(nm) {
chisq.test(table(data[[nm]], data[[ev]]))
})
# Warning messages:
# 1: In chisq.test(table(data[[nm]], data[[ev]])) :
# Chi-squared approximation may be incorrect
(because I'm using a bad example for the test, there are a lot of warnings here; this can be ignored when using mtcars
because it is really not a good dataset for this test.)
summaries <- lapply(models, summary)
str(summaries[1:2])
# List of 2
# $ : 'summaryDefault' chr [1:9, 1:3] " 1" " 1" " 1" " 1" ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr [1:9] "statistic" "parameter" "p.value" "method" ...
# .. ..$ : chr [1:3] "Length" "Class" "Mode"
# $ : 'summaryDefault' chr [1:9, 1:3] " 1" " 1" " 1" " 1" ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : chr [1:9] "statistic" "parameter" "p.value" "method" ...
# .. ..$ : chr [1:3] "Length" "Class" "Mode"
Upvotes: 2