In the following example, I want to extract NA as a level and display it in the table just as other levels. The levels()
function doesn't work with NA value. Is there any other way to deal with this problem?
n=1000
comorbid<-sample(c(rep("diabetes",2),
rep("hypertension",5),
"cirrhosis","stroke","heartfailure",
"renalfailure",rep("COPD",3)),
n,
replace=T)
comorbid[sample(1:n,50)]<-NA
mort<-sample(c(rep("alive",4),
"dead"),n,replace=T)
table.cat<-data.frame(matrix(rep(999,7),nrow=1))
table<-table(comorbid,useNA="always")
per<-prop.table(table)
table.sub<-table(comorbid,mort,useNA="always")
per.sub<-prop.table(table.sub,2)
p<-tryCatch({#using fisher's test when scarce data
chisq.test(table.sub)$p.value
}, warning = function(w) {
fisher.test(table.sub,
workspace = 10e7)$p.value
})
frame<-data.frame(No.tot=as.data.frame(table)[,"Freq"],
per.tot=as.data.frame(per)[,"Freq"],
No.1=as.data.frame.matrix(table.sub)[,"alive"],
per.1=as.data.frame.matrix(per.sub)[,"alive"],
No.2=as.data.frame.matrix(table.sub)[,"dead"],
per.2=as.data.frame.matrix(per.sub)[,"dead"],
p=p)
rownames(frame)<-paste("comorbid",levels(comorbid),sep="_")