[Tex/LaTex] Reporting R Results in LaTeX

r

I´m writing my thesis in LaTeX (using Overleaf) and I analyzed some data in R. So I have a R script where I perform a bunch of tests and regressions. Now I want to e.g. include the t-statistic and p-value in the Text.

x <- rnorm(10, 180, 10)
y <- rnorm(10, 150, 10)

Our Hypothesis that x is taller than y was accepted (t =t.test(x , y)$statisic; p = t.test(x, y)$p.value).

S.t. In the final pdf it says:

Our Hypothesis that x is taller than y was accepted (t =-7.8841, p = 0.000).

What is the easiest way to do this? What is the workflow?

I`d be thankful for any advice using LaTeX. Even more so for advice for Overleaf.

Best Answer

A example code is worth a thousand words:

\documentclass{article}
\begin{document}
<<echo=F,results="hide">>=
set.seed(100)
options(scipen=0)
x <- rnorm(10, 155, 10)
y <- rnorm(10, 150, 10)
accept <- if (t.test(x,y)$p.value>0.05) {print("rejected")} else {print("accepted")}
@
Our hypothesis that $x$ is taller than $y$ was \Sexpr{accept}  (%
t=\Sexpr{round(t.test(x,y)$statistic,2)}; 
p=\Sexpr{signif(t.test(x,y)$p.value,2)}).
\end{document}

Save it with the extension .Rtex in Overleaf or .Rnw if you are using Rstudio. Of course, in this case you should have installed R and the knitr package to convert the .Rnw file to a true LaTeX file (.tex) and a LaTeX distribution to produce the .tex to .pdf conversion. In any case the result will be:

Our hypothesis that x is taller than y was rejected (t=0.76; p=0.46).

Or, replacing "155" by "180" (6th row):

Our hypothesis that x is taller than y was accepted (t=8.46; p=3.4 × 10⁷).