Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a latex table from ftable object in R

Let me create some data before I ask my question.

 my.data <- data.frame(A = sample(seq(1,100,by=5),10,replace=TRUE),W = rnorm(10),X =sample(1:10),Y = sample(c("yes", "no"), 10, replace = TRUE),Z=sample(c('a','b','c','d'),10,replace=TRUE))

attach(my.data)

my.d <- xtabs(W~Z+Y+A);my.d
table.data <- ftable(my.d)

result1 <- round(table.data,2)

result1 looks like ..

      A     6    11    16    26    71    76    86    91
Z Y                                                    
a no     0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00
 yes    0.00  0.56  0.00  0.00  0.00  0.79  0.00  0.01

b no     0.61  0.00 -0.22  0.14  0.00  0.00 -0.08  1.71
  yes    0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00

c no     0.00  0.00  0.00  0.00 -0.08  0.00  0.00  0.00
  yes    0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00

d no     0.00  0.00  0.00  0.00  1.00  0.00  0.00  0.00
  yes    0.00  0.00  0.00  0.00  0.00  0.00  0.00  0.00

I am actually writing an article using knitr package. Is there a way to transform result1 into a latex table automatically when my *.rnw file is complied ?

I tried with xtable but got the following error...

Error in UseMethod("xtable") :   no applicable method for 'xtable' applied to an object of class "ftable"

Thank you @DWin and @Yihui. Apart from latex(), I also used xtable as stated under

print(xtable(ftable2data.frame(result1)))

To remove unnecessary row names I did the following

print(xtable(ftable2data.frame(result1)),include.rownames=FALSE)
like image 275
Stat-R Avatar asked Mar 11 '12 19:03

Stat-R


3 Answers

You can use the package xtable:

library(xtable)
mytable=ftable(mydata)
print(
  xtable(format(mytable)),file="~/Desktop/mytable.tex"
)

I don't know how it compares to the other options given.

like image 51
user109114 Avatar answered Nov 09 '22 13:11

user109114


As an alternative, memisc provides toLatex methods for ftable objects.

library(memisc)
toLatex(result1)
like image 22
David Avatar answered Nov 09 '22 14:11

David


Method 1:

require(MIfuns)
require(Hmisc)
latex(ftable2data.frame(result1))
like image 29
IRTFM Avatar answered Nov 09 '22 15:11

IRTFM