Adding titles to xtable

守給你的承諾、 提交于 2019-12-13 13:24:46

问题


I'm not sure if this is an R question or a Sweave question. I"m looking at students' marks from 2 time points in a simple table (Grade 3 and Grade 6). I've created the table and it prints, however I want to add labels so people know which mark is from which Grade.

My Sweave code is:

<<MakeData,results='asis'>>=
library(xtable)
Grade3 <- c("A","B","B","A","B","C","C","D","A","B","C","C","C","D","B","B","D","C","C","D")
Grade6 <- c("A","A","A","B","B","B","B","B","C","C","A","C","C","C","D","D","D","D","D","D")
Cohort <- table(Grade3,Grade6)
print(xtable(Cohort))
@

I get a nice table with counts, however both rows and columns have the same notation. How do I add a label to make it clearer?


回答1:


To change the labels for Cohort, change the column and rownames:

rownames(Cohort) <- 1:4
colnames(Cohort) <- 5:8

You also add table titles to the xtable call:

print(xtable(Cohort, caption = 'My Title'), caption.placement = 'top')

You can use caption.placement to tell where to put the caption.

EDIT:

Based on the comments, I didn't answer the question above. To make xtable print more like table with the labels above the levels, you use add.to.row in the print.xtable function:

addtorow <- list()
addtorow$pos <- list()
addtorow$pos[[1]] <- 0
addtorow$pos[[2]] <- 0
addtorow$command <- c('& & Grade 6 & & \\\\\n', "Grade 3 & A & B & C & D \\\\\n")
print(xtable(Cohort, caption = 'My Title'), caption.placement = 'top', 
      add.to.row = addtorow, include.colnames = FALSE)

add.to.row takes a list with two elements: pos and command. pos is a list of whose length is the same as command which is a vector. Each element of pos is the line in the table where you are placing the corresponding element of command.

Here, I want the first two lines to be where the labels go. I set the first and second elements of pos to 0 to indicate that I am putting things on the top of the table. The 0 position is that between the two horizontal rules in the table.

The \\\\\n produce the '\\' in the LaTeX code that is used at the end of each line of a table plus a newline character.

The help for xtable has a good example of add.to.row for more information.



来源:https://stackoverflow.com/questions/19846796/adding-titles-to-xtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!