[Tex/LaTex] Cross-referencing tables generated by xtable

cross-referencingknitrrxtable

I'd like to cross-reference a table that I generated with xtable in R. I cannot able to. Here is what I did:

\documentclass{article}
\begin{document}
Look at \ref{tab:mytable}.
<<echo=FALSE,results='asis'>>=
  library(xtable, car)
  print(xtable(x=mtcars[1:5,1:5]), label = "tab:mytable")
@
\end{document}

Any ideas?

Best Answer

If you look at your example, the table does not have a number. I assume you want to reference the table number, so first we must give the table a number. To do this, use the caption argument.

Second, when using xtable, you have to be careful with which arguments you want to give to xtable and which arguments to print.xtable. You are currently passing the label argument to print.xtable but if you look at ?print.xtable there is no label argument.

Taking into account both of the above points gives us:

\documentclass{article}
\begin{document}
Look at \ref{tab:mytable}.
<<echo=FALSE,results='asis'>>=
  library(xtable, car)
  print(xtable(x=mtcars[1:5,1:5], caption = "example", label = "tab:mytable"))
@
\end{document}

The above code gives me the following output (note that you may have to run your latex/pdflatex command more than once):

enter image description here

Related Question