2
votes

I am trying to produce a simple crosstable in R and have that exported to latex using knitr in Rstudio.

I want the table to look like a publishable table, with row header, column header, and subheaders for each category of the variable in the column. Since my table have identical categories for rows and columns, I wish to replace the column level headers with numbers. See example below:

                                      Profession Mother
 ProfesssionFather                1.          2.            3.
 1. Bla                      frequency   frequency    frequency
 2. blahabblab
 3. blahblahblah

I am getting close with 'xtable' (I can't get row and column headers to print, and not multicolumn header), and the 'tables' package (I can't replace the column categories with numbers).

Minimal example:

work1 <- paste("LongString", 1:10, sep="")
work2 <- paste("LongString", 1:10, sep="")
t <- table(work1, work2) # making table
t # table with repated row/column names
colnames(t) <- paste(1:10, ".", sep="") # replacing column names with numeric values

xtable(t) # headers are omitted for both rows and columns

work <- data.frame(cbind(work1, work2)) # prepare for use of tabular
tabular((FathersProfession=work1) ~ (MothersProfession=work2), data=work) # have headers, but no way to change column categories from "LongString"x to numeric. 
1

1 Answers

1
votes

You need to assign the output of the tabular function to a named object:

 tb <- tabular((FathersProfession=work1) ~ (MothersProfession=work2), data=work)
 str(tb)

It should be obvious that the data is in a list and that the column-names are in the attribute that begins:

 - attr(*, "colLabels")= chr [1:2, 1:10] "MothersProfession" "LongString1" NA "LongString10" ...

So

 attr(tb,  "colLabels") <- 
       gsub("LongString", "" , attr(tb,  "colLabels") )

This is then the output to the screen, but the output to a latex device would be different.

> tb

                   MothersProfession                   
 FathersProfession 1                 10 2 3 4 5 6 7 8 9
 LongString1       1                 0  0 0 0 0 0 0 0 0
 LongString10      0                 1  0 0 0 0 0 0 0 0
 LongString2       0                 0  1 0 0 0 0 0 0 0
 LongString3       0                 0  0 1 0 0 0 0 0 0
 LongString4       0                 0  0 0 1 0 0 0 0 0
 LongString5       0                 0  0 0 0 1 0 0 0 0
 LongString6       0                 0  0 0 0 0 1 0 0 0
 LongString7       0                 0  0 0 0 0 0 1 0 0
 LongString8       0                 0  0 0 0 0 0 0 1 0
 LongString9       0                 0  0 0 0 0 0 0 0 1

enter image description here