Skip to content
Prev 299437 / 398503 Next

Tables extraction in R ?

On 07/07/2012 03:23 AM, Greeknovice wrote:
Hi Greeknovice,
Combining results from different functions into a specified format is a 
common problem in R. As you noted, it has to look like some default 
format used in another system. The flexibility of R allows you to do 
this, but you have to write a function or two like this:

table_with_prop_test<-function(x) {
  counts<-table(x)
  ncounts<-length(counts)
  totalx<-sum(counts)
  pcts<-round(100*counts/totalx,1)
  X2<-df<-p<-lcl<-ucl<-rep(0,ncounts)
  for(i in 1:ncounts) {
   proptest<-prop.test(counts[i],totalx)
   X2[i]<-round(proptest$statistic,2)
   df[i]<-proptest$parameter
   p[i]<-round(proptest$p.value,3)
   lcl[i]<-round(proptest$conf.int[1],3)
   ucl[i]<-round(proptest$conf.int[2],3)
  }
  tptmat<-cbind(counts,pcts,X2,df,p,lcl,ucl)
  return(tptmat)
}

Then if you want to turn the result into an image, you can do something 
like this:

library(plotrix)
png("table_with_prop_test.png",height=200)
plot(1:5,type="n",axes=FALSE,xlab="",ylab="")
addtable2plot(1,3,table_with_prop_test(x),
  display.rownames=TRUE)
dev.off()

Jim