2

我正在尝试在 R 中生成一个简单的交叉表,并使用 Rstudio 中的 knitr 将其导出到乳胶。

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

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

我正在接近'xtable'(我无法打印行和列标题,而不是多列标题)和'tables'包(我不能用数字替换列类别)。

最小的例子:

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. 
4

1 回答 1

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

在此处输入图像描述

于 2013-08-16T16:44:27.683 回答