Reputation: 479
I am new to knitr. I have made a practise .Rnw file with some very simple commands. For example:
\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")
@
When I click on "Compile PDF", I get a PDF with all the code (as I expect, since I didn't use echo = FALSE), as well as the plot itself and the print statement.
My question is: why do I not see "df" in Rstudio, in my "Environment" panel, like you "usually" when simply running a .R script in Rstudio? Clearly, R is running the code in the code chunk and producing the PDF. So why is there nothing in the Environment. If I run the R code in the .Rnw file "manually", I do get "df" in the Environment.
Am I missing something? I know it doesn't really matter, since my code still technically runs, but I find unituitive that Rstudio doesn't show anything in the Environment. Is there a reason for this?
Thanks.
Upvotes: 1
Views: 632
Reputation: 44907
The usual way to knit an Rnw file by clicking on Compile PDF
in RStudio does it in an independent R process. Your document won't see local variables in your workspace, and variables created in it won't last beyond the processing.
There are ways to change this. If you explicitly knit the process in the R console, e.g.
knitr::knit2pdf("file.Rnw")
then it will be able to see the variables in your local workspace, but changes it makes won't be saved. To also save results, use
knitr::knit2pdf("file.Rnw", envir = globalenv())
which says to evaluate the code in the global environment (i.e. your workspace).
Upvotes: 3