Search code examples
rlatexr-package

How to write an R example in Latex file


I am writing a latex file in Rstudio, and need to present an R example for an R package developed by myself. I noticed the published paper often has a format for the example as shown below, but I am not sure what functions they were using to generate this style, such as R>... How do we produce something like this?

enter image description here


Solution

  • I am unsure which OS you are using; here is an example to help guide the way.

    Recommended reading: https://ctan.org/pkg/listings?lang=en

    [![\documentclass{article}
    \usepackage{listings}
    \usepackage{xcolor}
    \usepackage{parskip}  
    \usepackage{hyperref}
    
    % Define colors
    \definecolor{codegreen}{rgb}{0,0.6,0}
    \definecolor{codegray}{rgb}{0.5,0.5,0.5}
    \definecolor{codepurple}{rgb}{0.58,0,0.82}
    \definecolor{linkcolor}{rgb}{0,0,0.8}  % Dark blue for links
    
    % Hyperref setup
    \hypersetup{
        colorlinks=true,
        linkcolor=linkcolor,
        urlcolor=linkcolor,
        pdftitle={Formatting Solution for 79010592},
        pdfauthor={Your Name}
    }
    
    % Console-style R code
    \lstdefinestyle{RConsoleStyle}{
        language=R,
        basicstyle=\ttfamily\small,
        backgroundcolor=\color{white},
        commentstyle=\color{codegreen},
        keywordstyle=\color{blue},
        stringstyle=\color{codepurple},
        breaklines=true,
        breakatwhitespace=true,
        showstringspaces=false,
        numbers=none,
        stepnumber=1,
        numberstyle=\tiny\color{codegray},
        tabsize=2,
        keepspaces=true,
        escapeinside={(*@}{@*)},
        literate=*{>}{{\textcolor{codegray}{>}}}{1}
    }
    
    \title{Formatting Solution for \href{https://stackoverflow.com/questions/79010592/how-to-write-an-r-example-in-latex-file}{79010592}}
    \author{Technophobe01}
    \date{\today}
    
    \begin{document}
    
    \maketitle
    
    \noindent Here is an example of R code formatted in a console-style using the listings package:
    
    \begin{lstlisting}\[style=RConsoleStyle\]
    (*@\textcolor{codegray}{R>}@*) library("simexaft")
    \end{lstlisting}
    
    Next, load the data that are properly organized with the variable names specified. In the example here, the data set named as BHS is included by issuing
    
    \begin{lstlisting}\[style=RConsoleStyle\]
    (*@\textcolor{codegray}{R>}@*) data("BHS")
    (*@\textcolor{codegray}{R>}@*) dataset <- BHS
    (*@\textcolor{codegray}{R>}@*) dataset$SBP <- log(dataset$SBP - 50)
    \end{lstlisting}
    
    \end{document}][1]][1]
    

    Here is the output:

    enter image description here

    I hope this points you in the right direction.