代码之家  ›  专栏  ›  技术社区  ›  Pryore

以PDF格式格式化表格,以便聚合时不重复列值

r
  •  0
  • Pryore  · 技术社区  · 7 年前

    我正在使用ToothGrowth数据集生成一个输出为pdf的表,使用以下代码:

    library(grid)
    library(extraGrid)
    
    > dput(ToothGrowth)
    structure(list(len = c(4.2, 11.5, 7.3, 5.8, 6.4, 10, 11.2, 11.2, 
    5.2, 7, 16.5, 16.5, 15.2, 17.3, 22.5, 17.3, 13.6, 14.5, 18.8, 
    15.5, 23.6, 18.5, 33.9, 25.5, 26.4, 32.5, 26.7, 21.5, 23.3, 29.5, 
    15.2, 21.5, 17.6, 9.7, 14.5, 10, 8.2, 9.4, 16.5, 9.7, 19.7, 23.3, 
    23.6, 26.4, 20, 25.2, 25.8, 21.2, 14.5, 27.3, 25.5, 26.4, 22.4, 
    24.5, 24.8, 30.9, 26.4, 27.3, 29.4, 23), supp = structure(c(2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("OJ", 
    "VC"), class = "factor"), dose = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
    0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 
    2, 2, 2, 2, 2, 2, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
    0.5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
    2)), class = "data.frame", row.names = c(NA, -60L))
    
    pdf("Test1.pdf", height = 20, width = 10)
    grid.table(ToothGrowth, rows = NULL, theme = ttheme_minimal())
    dev.off()
    

    正如您在输出中看到的(参见下图),剂量和supp列值在整个过程中重复。然而,我想格式化表格,使剂量和supp值在整个过程中不会重复,我附上了另一张照片,向您展示我到底想要什么。

    如果您能在这方面提供一些帮助,我将不胜感激,因为我不确定解决方案是在于数据争用还是pdf输出代码。

    enter image description here

    所需格式

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andre Elrico    7 年前

    您可以使用:

    TG1 <- ToothGrowth  # make a copy in this case, its a "build-in" dataset
    
    inds <- duplicated(TG1[,2:3]) # use duplicated in the respective column combination
    
    TG1[inds, 2:3] <- NA  # replace all dupe rows for your cols 2 and 3
    
    #TG1$supp <- as.character(TG1$supp) # if you want to use "", you need to convert from factor to character first.
    #TG1[inds, 2:3] <- "" # try out what works better for you.
    
    pdf("Test1.pdf", height = 20, width = 10)
    grid.table(TG1, rows = NULL, theme = ttheme_minimal())
    dev.off()