High school statistics teacher here, so sorry for the simple question (or maybe not so simple).
I'm running R to create a stem-and-leaf plot. I'm trying to turn a stem-and-leaf output from stem() into LaTeX. Here is what I've got so far:
y<- c(50, 26, 31, 57, 19, 24, 22, 23, 38, 13, 50, 13, 34, 23, 30, 49, 13, 15, 51)
stem(y)
I've tried to use xtables (because it works for my simple two-way tables) as such:
print(xtable(stem(y)), type="latex", latex.environments=c("center"), tabular.environment = "tabular", NA.string = "")
and I get this error:
Error in UseMethod("xtable") : no applicable method for 'xtable' applied to an object of class "NULL"
I've tried variations on the the options, but get similar results. From what I can figure, the output from stem() isn't a data frame or matrix, so xtables doesn't like it. I tried changing it to a data frame/matrix using as.data.frame() and as.matrix() but with no success. Any help would be appreciated. I've run a few google searches with no useful results and looked through the stackoverflow site. Any help would be appreciated.
I am assuming that you just want to export the result to latex, am I right?
You might want to try the following Sweave code, which passed the test:
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}
<<echo=F, results=tex>>=
y<- c(50, 26, 31, 57, 19, 24, 22, 23, 38, 13, 50, 13, 34, 23, 30, 49, 13, 15, 51)
stem(y)
@
\end{lstlisting}
\end{document}
Borrowing heavily from the solution provided by @DWin:
You can capture the output from a print statement with capture.output and translate it to Latex using latexTranslate in package HMisc:
library(Hmisc)
latexTranslate(capture.output(stem(y)))
[1] ""
[2] " The decimal point is 1 digit(s) to the right of the $|$"
[3] ""
[4] " 1 $|$ 33359"
[5] " 2 $|$ 23346"
[6] " 3 $|$ 0148"
[7] " 4 $|$ 9"
[8] " 5 $|$ 0017"
[9] ""
The stem function returns NULL. It only works via a side-effect of printing to the console device.
You could also use sink, but I'm guessing that is not much closer to your goal
sink("stem.out")
stem(y)
sink()
When I run this through the Hmisc function latex I get:
latex(readLines("stem.out")
#--------file output follows----
% latex.default(readLines("stem.out"))
%
\begin{table}[!tbp]
\begin{center}
\begin{tabular}{l}\hline\hline
\multicolumn{1}{c}{}\tabularnewline
\hline
\tabularnewline
The decimal point is 1 digit(s) to the right of the |\tabularnewline
\tabularnewline
1 | 33359\tabularnewline
2 | 23346\tabularnewline
3 | 0148\tabularnewline
4 | 9\tabularnewline
5 | 0017\tabularnewline
\tabularnewline
\hline
\end{tabular}
\end{center}
\end{table}
#--------- end of file ------
来源:https://stackoverflow.com/questions/7328354/stem-and-leaf-from-r-into-latex