如何在R代码块内创建R标记部分?有正确的代码显示

如何在R代码块内创建R标记部分?有正确的代码显示,r,pdf,latex,knitr,r-markdown,R,Pdf,Latex,Knitr,R Markdown,我目前正在使用rmarkdown编写一份报告,因此我想在r代码块中创建部分。我发现,借助于cat()和results=“asis”,这是可能的。 这个解决方案的问题是,我的R代码结果和代码没有像往常一样正确显示 比如说 --- title: "test" output: pdf_document --- ```{r, results='asis'} for (i in 1:10) { cat("\\section{Part:", i, "}") print(summary(lm(dat

我目前正在使用rmarkdown编写一份报告,因此我想在r代码块中创建部分。我发现,借助于cat()results=“asis”,这是可能的。 这个解决方案的问题是,我的R代码结果和代码没有像往常一样正确显示

比如说

---
title: "test"
output: pdf_document
---

```{r, results='asis'}
for (i in 1:10) {
  cat("\\section{Part:", i, "}")
  print(summary(lm(data=X, X1~X2))
  $\alpha = `r X[1,i]`$  
}
```
基本上就是这样,但这里仍然有两个问题:

  • summary()的R输出显示得非常奇怪,因为我猜它被解释为LaTeX代码
  • 我不能在这种环境下使用LaTeX公式,所以如果我想让每个部分都以一个等式结束,也可能使用一个R变量,这是不可能的
有人知道这方面的解决方案吗,或者是否有一种在循环中创建节并在这一节中包含R代码、R输出和LaTeX公式的变通方法

我非常感谢各种建议:)

使用降价和逐字记录环境 您可以使用
逐字
环境来包围R输出,使用四个
\
来转义代码

```{r, results='asis'}
for (i in 1:10) {
  cat("\\section{Part:", i, "}")
  cat("\\begin{verbatim}")
  print(summary(lm(data=mtcars, mtcars[,1]~ mtcars[,i])))
  cat("\\end{verbatim}")
  cat(paste0("$\\\\alpha$ = ", mtcars[1,i]))  
}
```

使用listings软件包更有趣一些 在某种程度上,当运行latex时,我倾向于退出markdown(.Rmd)并使用Swave(.Rnw),我发现这要容易得多,您可以检查.tex文件中发生的情况并找出问题所在

\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage[usename,dvipsnames]{xcolor}
% create a set of colors
\definecolor{mygreen}{rgb}{0,0.6,0} 
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
% create a listings environment suitable for R code
\lstset{ %
  backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
  basicstyle=\footnotesize\ttfamily, % the size of the fonts that are used for the
  % code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},      % comment style
  deletekeywords={...},            % if you want to delete keywords from the given language
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
  frame=single,                    % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
  keywordstyle=\color{blue},       % keyword style
  language=R,                       % the language of the code
  morekeywords={*,...},            % if you want to add more keywords to the set
  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
  numbersep=5pt,                   % how far the line-numbers are from the code
  numberstyle=\tiny\color{mygray},   % the style that is used for the line-numbers
  rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
  showstringspaces=false,          % underline spaces within strings only
  showtabs=false,                  % show tabs within strings adding particular underscores
  stepnumber=2,                    % the step between two line-numbers. If it is 1, each line will be numbered
  stringstyle=\color{mymauve},      % string literal style
  tabsize=2,                       % sets default tabsize to 2 spaces
  title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
}
\title{test}
\begin{document}
\maketitle

<<r, results='asis'>>=
for (i in 1:10) {
  cat("\\section{Part:", i, "}")
  cat("\\begin{lstlisting}")
  print(summary(lm(data=mtcars, mtcars[,1]~ mtcars[,i])))
  cat("\\end{lstlisting}")
  cat(paste0("$\\\\alpha$ = ", mtcars[1,i]))  
}
@

\end{document}
\documentclass[a4paper]{article}
\usepackage{listings}
\usepackage[usename,dvipsnames]{xcolor}
%创建一组颜色
\定义颜色{mygreen}{rgb}{0,0.6,0}
\定义颜色{mygray}{rgb}{0.5,0.5,0.5}
\定义颜色{mymauve}{rgb}{0.58,0,0.82}
%创建适合R代码的列表环境
\lstset{%
backgroundcolor=\color{white}%,选择背景色;必须添加\usepackage{color}或\usepackage{xcolor}
basicstyle=\footnotesize\ttfamily%,用于
%代码
breakatwhitespace=false,%set如果自动中断只发生在空白处
特征线=true,%sets自动换行
captionpos=b,%s将标题位置设置为底部
commentstyle=\color{mygreen},%commentstyle
deletekeywords={…}%,如果要从给定语言中删除关键字
如果要在代码中添加LaTeX,则escapeinside={\%*}{*},%
extendedchars=true,%s允许使用非ASCII字符;仅用于8位编码,不适用于UTF-8
frame=single%,在代码周围添加一个框架
keepspaces=true,%s在文本中保留空格,用于保留代码缩进(可能需要列=灵活)
关键字样式=\color{blue},%keywordstyle
language=R,代码的语言%
morekeywords={*,…}%,如果要向集合中添加更多关键字
数字=左侧,将行号放在何处;可能的值为(无、左、右)
numbersp=5pt,行号与代码的距离百分比
numberstyle=\tiny\color{mygray}%,用于行号的样式
rulecolor=\color{black}%,如果未设置,框架颜色可能会在非黑色文本中的换行符上更改(例如注释(此处为绿色))
showspaces=false,%show spaces where添加特定下划线;它覆盖“showstringspaces”
showstringspaces=false,仅在字符串中加下划线%s
showtabs=false,%showtabs在添加特定下划线的字符串中显示
stepnumber=2%,两个行号之间的步长。如果为1,则每行都将被编号
stringstyle=\color{mymauve},%string文字样式
tabsize=2%,将默认tabsize设置为2个空格
title=\lstname%显示包含在\lsInputListing中的文件名;也可以尝试使用caption代替title
}
\标题{测试}
\开始{document}
\maketitle
=
因为(我在1:10){
类别(“\\section{Part:,i,“}”)
cat(“\\begin{lstlisting}”)
打印(摘要(lm(数据=mtcars,mtcars[,1]~mtcars[,i]))
类别(“\\end{lstlisting}”)
cat(粘贴0(“$\\\\alpha$=”,mtcars[1,i]))
}
@
\结束{document}