Stroke of insight on my part/cheaters work-around. I just created a second data.frame that had the names of the cat variables from catvars, and the position within the list, and then with a few steps, correctly merged the two data.frames together and removed the extra columns.
#function
make.table<-function(catvars,group,data){
attach(data)
get.chi.stuff<-function(cat, group){
long <- table(cat,group)
test<-chisq.test(cat,group)
kk<-c(test$statistic,test$p.value,test$method)
res <- data.frame(matrix(NA,nrow(long),7))
names(res) <- c("list", "Response", "Group1.Freq", "Group2.Freq",
"Test.Stat", "p.value", "method")
res[1,1] <- deparse(substitute(cat))
res[,2] <- row.names(long)
res[,3:4] <- long[,1:2]
res[1,5:7] <- kk
return(res)
}
tabless<-do.call(rbind.data.frame,lapply(data[,catvars],get.chi.stuff,group=group))
length<-1:length(tabless[,1])
table2<<-data.frame(length,tabless)
detach(data)
}
#list of variables of interest
catvars<-c("cat1", "cat2", "cat3","cat4")
#call to function
make.table(catvars=catvars,group=group, data=one)
Variable<-catvars
numbersss<-match(catvars,catvars)
list<-gsub("\\s","",paste("X[[",numbersss,"L]]"))
matched<-data.frame(list,Variable)
newtable<-merge(matched,table2,by="list", all=TRUE)
finaltable<-newtable[with(newtable, order(length)), ]
drops <- c("row.names", "list", "length")
cattable<-finaltable[,!(names(finaltable) %in% drops)]
Variable Response Group1.Freq Group2.Freq Test.Stat p.value method
cat1 1 26 26 0.40 0.52 Pearson's Chi-squared test with Yates' continuity correction
NA 2 28 20 NA NA NA
cat2 1 17 12 1.16 0.76 Pearson's Chi-squared test
NA 2 11 13 NA NA NA
NA 3 13 9 NA NA NA
NA 4 13 12 NA NA