Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding titles to xtable

Tags:

r

sweave

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?

like image 764
GregRousell Avatar asked Dec 19 '22 21:12

GregRousell


1 Answers

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.

like image 83
Christopher Louden Avatar answered Jan 11 '23 23:01

Christopher Louden