Search code examples
rlatex

Incorporating a previously defined object into text block in LaTex file in R Studio


I have a LaTex file in R where I have a code chunk that is calling a dataset and assigning the dimensions to an object. I want to be able to set the code to not evaluate so that I can put the variables into a text block that will show up in the pdf output.

Below is an example of what I'm trying to do using a common R dataset.

The R chunk would look like this:

<<>>=
library(MASS)
data("crabs")
obs <- as.list(dim(crabs))
vars <- as.list(dim(crabs))
@

But I want this to not show up in the output, and instead have it show up as a text block that uses the obs and vars objects to create a sentence that describes the dataset.

Here is what I have tried without luck:

{\bf Dataset Dimensions}
``The crabs data set has \newcommand\x{obs[1])} observations
and \newcommand\x{obs[2])} variables.'' 

If is is working correctly, it should show up in the output as a sentence that says:

"The crabs data set has 200 observations and 8 variables."


Solution

  • The following syntax works in .Rnw files for LaTex output to pdf.

    \newline The crabs data set has \Sexpr{(obs[1])} observations and \Sexpr{(obs[2])} variables.