Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an R example in Latex file

Tags:

r

latex

r-package

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

like image 578
Phoebe Avatar asked Oct 20 '25 02:10

Phoebe


1 Answers

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

like image 116
Technophobe01 Avatar answered Oct 21 '25 16:10

Technophobe01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!