knitr:为什么在我编译 .Rnw 文件时 "environment" 面板中没有任何内容

knitr: why does nothing appear in the "environment" panel when I compile my .Rnw file

我是 knitr 的新手。我用一些非常简单的命令制作了一个练习 .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")
@

当我点击 "Compile PDF" 时,我得到了一个包含所有代码的 PDF(如我所料,因为我没有使用 echo = FALSE),以及绘图本身和打印语句。

我的问题是:为什么我在 Rstudio 中看不到 "df",在我的 "Environment" 面板中,就像您一样 "usually" 运行在 Rstudio 中创建 .R 脚本?显然,R 正在 运行ning 代码块中的代码并生成 PDF。那么为什么环境中什么都没有。如果我 运行 .Rnw 文件中的 R 代码 "manually",我会在环境中得到 "df"。

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

谢谢。

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

有很多方法可以改变这一点。如果您在 R 控制台中明确编织该过程,例如

knitr::knit2pdf("file.Rnw")

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

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

表示在全局环境(即您的工作区)中评估代码。