R - knitr:"environment"为什么当我编译我的.Rnw 文件



我是针织新手。我已经做了一个练习.带有一些非常简单命令的 rnw 文件。例如:

documentclass[12pt, a4paper]{article}
usepackage[utf8]{inputenc} 
usepackage{hyperref}
hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
}
usepackage{caption}
captionsetup[figure]{labelfont=bf, labelsep=period}
captionsetup[table]{labelfont=bf, labelsep=period}
setlength{parindent}{0pt}

title{My very first LaTeX/knitr document!}
date{April 2019}

begin{document}
maketitle
begingroup
hypersetup{linkcolor=black} % force independent link colours in table of    contents
tableofcontents
endgroup
newpage
section{Basics}
subsection{Using no options}
First, let's try and a show a chunk of code along with a plot and print() message.
<<first-chunk>>=
# Make a simple dataframe:
setwd("/home/user/Documents/testing-area/knitr/")
df <- data.frame(A = c(1,2,3), B = c("A", "B", "C"))
plot(df$A,df$B)
print("hello")
@

当我单击"编译PDF"时,我得到一个包含所有代码的PDF(正如我所期望的那样,因为我没有使用echo = FALSE(,以及绘图本身和打印语句。

我的问题是:为什么我在 Rstudio 中的"环境"面板中看不到"df",就像您"通常"在简单地运行 .Rstudio 中的 R 脚本?显然,R 正在代码块中运行代码并生成 PDF。那么为什么环境中什么都没有。 如果我在 .Rnw 文件"手动",我确实在环境中得到"df"。

我错过了什么吗?我知道这并不重要,因为我的代码在技术上仍然可以运行,但我发现 Rstudio 在环境中不显示任何内容是不恰当的。这有什么原因吗?

谢谢。

通过在 RStudio 中单击 Compile PDF 来编织 Rnw 文件的常用方法是在独立的 R 进程中完成的。 您的文档不会在工作区中看到局部变量,并且在其中创建的变量不会持续到处理之后。

有很多方法可以改变这一点。 如果在 R 控制台中显式编织流程,例如

knitr::knit2pdf("file.Rnw")

然后,它将能够看到本地工作区中的变量,但它所做的更改将不会保存。 要同时保存结果,请使用

knitr::knit2pdf("file.Rnw", envir = globalenv())

它说要评估全局环境(即您的工作区(中的代码。

最新更新