问题
I have an RMarkdown document with some R code in it. The code works fine when I'm running it interactively in the console. However, when I try to knit the document (using the "knit" button in RStudio), R throws error messages that some objects cannot be found.
回答1:
When you compile a document (using the "knit" button in RStudio), knitting takes place in a separate R session. Therefore, your document must be self-contained:
- Objects from the Global Environment of your interactive sessions are not available when knitting. You must create/load all objects from within your document.
- You must load all packages used from within your document.
Also note that while knitting, your working directory is changed to the directory containing your document (by default). Therefore, relative paths (for example, paths to data sets you want to read) might not point to the expected files.
来源:https://stackoverflow.com/questions/62563941/code-works-interactively-but-not-while-knitting