I have a dataframe with following data:
age.cat ds.cat finalstate
<65 AGN dead
<65 AGN alive
<65 PC alive
65+ AMI alive
65+ PC dead
<65 AMI alive
For every level of ds.cat
factor variable I need to perform Fisher test for age.cat
and finalstate
variables.
I tried to do it by several ways but was not received what I need. The following R code doesn't produce desired result:
library(descr)
# 1 syntax - doesn't work
by(split(df, df$ds.cat), CrossTable(age.cat, finalstate, prop.chisq = FALSE, fisher = TRUE))
# 2 syntax - doesn't work
sapply( split(df, df$ds.cat), function(x) CrossTable(age.cat, finalstate, prop.chisq = FALSE, fisher = TRUE) )
# 3 syntax - doesn't work
for(i in 1:nlevels(ds.cat)){
curcat <- subset(df, ds.cat == ds.cat[i])
CrossTable(age.cat[ds.cat == ds.cat[i]], finalstate[ds.cat == ds.cat[i]], prop.chisq = FALSE, fisher = TRUE, data = curcat)
}
Please could anyone suggest how to perform Fisher test for age.cat
and finalstate
variables for every level of ds.cat
factor variable?
Resolved!
Thank you so much for all of you!
This code with CrossTable
produces an error
Error in chisq.test(t, correct = FALSE) :
'x' must at least have 2 elements
But thanks for @BenBolker the base fisher.test
function works well in your code
l <- split(arf.mort, arf.mort$ds.cat)
lapply(l, function(x) fisher.test(x$age.cat, x$finalstate))
as well as works well
by(arf.mort, arf.mort$ds.cat, function(x){ fisher.test(x$age.cat, x$finalstate) })