【问题标题】:Simple crosstable with row- and multicolumn columnnames from R to latex具有从 R 到 Latex 的行和多列列名的简单交叉表
【发布时间】:2013-08-16 10:36:54
【问题描述】:

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

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

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

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

小例子:

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. 

【问题讨论】:

    标签: r latex frequency


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多