从R到乳胶的行和多列列名称的简单交叉表

时间:2013-08-16 10:36:55

标签: r latex frequency

我正在尝试在R中生成一个简单的crosstable,并使用Rstudio中的knitr将其导出为latex。

我希望该表看起来像一个可发布的表,列中包含变量的每个类别的行标题,列标题和子标题。由于我的表具有相同的行和列类别,我希望用数字替换列级标题。见下面的例子:

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

我越来越接近'xtable'(我无法打印行和列标题,而不是多列标题),以及'tables'包(我不能用数字替换列类别)。< / p>

最小例子:

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 个答案:

答案 0 :(得分:1)

您需要将tabular函数的输出分配给命名对象:

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

很明显,数据在列表中,并且列名在开始的属性中:

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

所以

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

然后输出到屏幕,但乳胶设备的输出会有所不同。

> 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