![在 Latex 中插入 R 代码](https://linux22.com/image/356472/%E5%9C%A8%20Latex%20%E4%B8%AD%E6%8F%92%E5%85%A5%20R%20%E4%BB%A3%E7%A0%81.png)
答案1
我不会找出 R Studio 如何设计代码的所有可能情况。但也许这会给你一些启发。
\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}
可能更容易的是,只需根据listings
lstlang3.sty 中的定义定义一种包含您想要的内容的新语言(或变体)。R 的定义如下。
\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
}%
我怀疑您不想要大多数这些关键词。
答案2
有多种方法可以将任何编程语言的代码包含到 LaTeX 中。
只是逐字逐句
\begin{verbatim}
# Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
\end{verbatim}
自定义列表
\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 包装(精美亮点)
\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}
或选择 minted 的颜色样式
添加\usemintedstyle{monokai}
序言