How can I define the color for the \listings package to display R code in Latex to get the result exactly like in the R Studio platform (example like in the figure)?
2 Answers
I'm not going to find every possible case of how R studio styles code. But maybe this will get you started.
\documentclass{article}
\usepackage[svgnames]{xcolor}
\usepackage{listings}
\lstset{language=R,
basicstyle=\small\ttfamily,
stringstyle=\color{DarkGreen},
otherkeywords={0,1,2,3,4,5,6,7,8,9},
morekeywords={TRUE,FALSE},
deletekeywords={data,frame,length,as,character},
keywordstyle=\color{blue},
commentstyle=\color{DarkGreen},
}
\begin{document}
\begin{lstlisting}
#Calculate CE for each counterparty
Value.A <- data.frame() #MTM value of each contract within cp A
# ...
for(i in 1:length(foo)){
if(isTrue(as.character(portfolio_data[i,1])=="A")==TRUE){
# ...
}
}
\end{lstlisting}
\end{document}
It may be easier to simply define a new language (or variant) that contains exactly what you want based off of listings
's definition which is in lstlang3.sty. The definition for R is this.
\lst@definelanguage{R}%
{keywords={abbreviate,abline,abs,acos,acosh,action,add1,add,%
aggregate,alias,Alias,alist,all,anova,any,aov,aperm,append,apply,%
approx,approxfun,apropos,Arg,args,array,arrows,as,asin,asinh,%
atan,atan2,atanh,attach,attr,attributes,autoload,autoloader,ave,%
axis,backsolve,barplot,basename,besselI,besselJ,besselK,besselY,%
beta,binomial,body,box,boxplot,break,browser,bug,builtins,bxp,by,%
c,C,call,Call,case,cat,category,cbind,ceiling,character,char,%
charmatch,check,chol,chol2inv,choose,chull,class,close,cm,codes,%
coef,coefficients,co,col,colnames,colors,colours,commandArgs,%
comment,complete,complex,conflicts,Conj,contents,contour,%
contrasts,contr,control,helmert,contrib,convolve,cooks,coords,%
distance,coplot,cor,cos,cosh,count,fields,cov,covratio,wt,CRAN,%
create,crossprod,cummax,cummin,cumprod,cumsum,curve,cut,cycle,D,%
data,dataentry,date,dbeta,dbinom,dcauchy,dchisq,de,debug,%
debugger,Defunct,default,delay,delete,deltat,demo,de,density,%
deparse,dependencies,Deprecated,deriv,description,detach,%
dev2bitmap,dev,cur,deviance,off,prev,,dexp,df,dfbetas,dffits,%
dgamma,dgeom,dget,dhyper,diag,diff,digamma,dim,dimnames,dir,%
dirname,dlnorm,dlogis,dnbinom,dnchisq,dnorm,do,dotplot,double,%
download,dpois,dput,drop,drop1,dsignrank,dt,dummy,dump,dunif,%
duplicated,dweibull,dwilcox,dyn,edit,eff,effects,eigen,else,%
emacs,end,environment,env,erase,eval,equal,evalq,example,exists,%
exit,exp,expand,expression,External,extract,extractAIC,factor,%
fail,family,fft,file,filled,find,fitted,fivenum,fix,floor,for,%
For,formals,format,formatC,formula,Fortran,forwardsolve,frame,%
frequency,ftable,ftable2table,function,gamma,Gamma,gammaCody,%
gaussian,gc,gcinfo,gctorture,get,getenv,geterrmessage,getOption,%
getwd,gl,glm,globalenv,gnome,GNOME,graphics,gray,grep,grey,grid,%
gsub,hasTsp,hat,heat,help,hist,home,hsv,httpclient,I,identify,if,%
ifelse,Im,image,\%in\%,index,influence,measures,inherits,install,%
installed,integer,interaction,interactive,Internal,intersect,%
inverse,invisible,IQR,is,jitter,kappa,kronecker,labels,lapply,%
layout,lbeta,lchoose,lcm,legend,length,levels,lgamma,library,%
licence,license,lines,list,lm,load,local,locator,log,log10,log1p,%
log2,logical,loglin,lower,lowess,ls,lsfit,lsf,ls,machine,Machine,%
mad,mahalanobis,make,link,margin,match,Math,matlines,mat,matplot,%
matpoints,matrix,max,mean,median,memory,menu,merge,methods,min,%
missing,Mod,mode,model,response,mosaicplot,mtext,mvfft,na,nan,%
names,omit,nargs,nchar,ncol,NCOL,new,next,NextMethod,nextn,%
nlevels,nlm,noquote,NotYetImplemented,NotYetUsed,nrow,NROW,null,%
numeric,\%o\%,objects,offset,old,on,Ops,optim,optimise,optimize,%
options,or,order,ordered,outer,package,packages,page,pairlist,%
pairs,palette,panel,par,parent,parse,paste,path,pbeta,pbinom,%
pcauchy,pchisq,pentagamma,persp,pexp,pf,pgamma,pgeom,phyper,pico,%
pictex,piechart,Platform,plnorm,plogis,plot,pmatch,pmax,pmin,%
pnbinom,pnchisq,pnorm,points,poisson,poly,polygon,polyroot,pos,%
postscript,power,ppoints,ppois,predict,preplot,pretty,Primitive,%
print,prmatrix,proc,prod,profile,proj,prompt,prop,provide,%
psignrank,ps,pt,ptukey,punif,pweibull,pwilcox,q,qbeta,qbinom,%
qcauchy,qchisq,qexp,qf,qgamma,qgeom,qhyper,qlnorm,qlogis,qnbinom,%
qnchisq,qnorm,qpois,qqline,qqnorm,qqplot,qr,Q,qty,qy,qsignrank,%
qt,qtukey,quantile,quasi,quit,qunif,quote,qweibull,qwilcox,%
rainbow,range,rank,rbeta,rbind,rbinom,rcauchy,rchisq,Re,read,csv,%
csv2,fwf,readline,socket,real,Recall,rect,reformulate,regexpr,%
relevel,remove,rep,repeat,replace,replications,report,require,%
resid,residuals,restart,return,rev,rexp,rf,rgamma,rgb,rgeom,R,%
rhyper,rle,rlnorm,rlogis,rm,rnbinom,RNGkind,rnorm,round,row,%
rownames,rowsum,rpois,rsignrank,rstandard,rstudent,rt,rug,runif,%
rweibull,rwilcox,sample,sapply,save,scale,scan,scan,screen,sd,se,%
search,searchpaths,segments,seq,sequence,setdiff,setequal,set,%
setwd,show,sign,signif,sin,single,sinh,sink,solve,sort,source,%
spline,splinefun,split,sqrt,stars,start,stat,stem,step,stop,%
storage,strstrheight,stripplot,strsplit,structure,strwidth,sub,%
subset,substitute,substr,substring,sum,summary,sunflowerplot,svd,%
sweep,switch,symbol,symbols,symnum,sys,status,system,t,table,%
tabulate,tan,tanh,tapply,tempfile,terms,terrain,tetragamma,text,%
time,title,topo,trace,traceback,transform,tri,trigamma,trunc,try,%
ts,tsp,typeof,unclass,undebug,undoc,union,unique,uniroot,unix,%
unlink,unlist,unname,untrace,update,upper,url,UseMethod,var,%
variable,vector,Version,vi,warning,warnings,weighted,weights,%
which,while,window,write,\%x\%,x11,X11,xedit,xemacs,xinch,xor,%
xpdrows,xy,xyinch,yinch,zapsmall,zip},%
otherkeywords={!,!=,~,$,*,\&,\%/\%,\%*\%,\%\%,<-,<<-,_,/},%
alsoother={._$},%
sensitive,%
morecomment=[l]\#,%
morestring=[d]",%
morestring=[d]'% 2001 Robert Denham
}%
I suspect you don't want most of those keywords.
-
1
-
1@Duy, presumably some other package has used
\RequirePackage{color}
which is causing a conflict. Without the code you're using that causes an error, I'm not sure precisely. One possibility is to provide any necessaryxcolor
package options to the\documentclass
.– TH.Jun 9, 2017 at 0:45 -
There are several ways to include code of any programming language into LaTeX.
Just verbatim
\begin{verbatim}
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
\end{verbatim}
Custom listing
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\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{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true, captionpos=b,
keepspaces=true, numbers=left,
numbersep=5pt, showspaces=false,
showstringspaces=false, showtabs=false, tabsize=2}
\lstset{style=mystyle}
\begin{document}
\begin{lstlisting}[language=R]
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
\end{lstlisting}
\end{document}
Minted package (beautiful Highlighting)
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{R}
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
\end{minted}
\end{document}
or choose colour styles for minted
add \usemintedstyle{monokai}
in preambula
listings
manual describes how to set the style for various things like keywords and comments. You'll need to play with the various options until you get the color scheme you want. If there's something particularly tricky, you should ask about that specifically.listings
. Have you considered usingminted
for this - I believe Pygments (which is actually purpose built for syntax highlighting code) does support R? You could presumably define your own colour scheme if necessary.