RStudio中RSweave文件加载tidyverse库后fancyhdr包编译错误排查求助
Hey there, let's break down what's happening with your RSweave document and how to fix it. You mentioned that everything works fine until you load tidyverse—then fancyhdr throws an undefined control sequence error, but removing the header code or skipping tidyverse makes it compile again. Here's why, and how to fix it for good.
Why This Happens
First, look at how you're defining your title and author in the LaTeX preamble:
\\makeatletter \\title{\\textbf{\\underline{Assignment 2}}}\\let\\thetitle\\@title \\author{Devansh Kamra} \\makeatother
You correctly map LaTeX's internal \\@title macro (which stores your title text) to your custom \\thetitle variable for the header. But you forgot to do the same for the author! Your fancyhdr setup uses \\rhead{\\theauthor}, but \\theauthor isn't actually defined anywhere.
So why didn't this error pop up before loading tidyverse? Two key reasons:
- Without
tidyverse, yourggplot(data = mpg)code fails, so the generated TeX document is super short. The\\maketitlecommand automatically sets the first page's style toplain, which overrides yourfancyheader setup—LaTeX never tries to render the header, so it never notices\\theauthoris missing. - When you load
tidyverse,ggplot2triggers knitr to include thepgfpackage (for vector graphics support). Thepgfpackage changes how LaTeX handles page styles, so even the first page checks the header macros. That's when it catches the undefined\\theauthorand throws the error.
The Overfull \\hbox warnings are just side effects from pgf's helper code being slightly too wide—they're not fatal, but we can ignore them once the core error is fixed.
The Fix
All you need to do is add one line to map LaTeX's internal \\@author macro to your \\theauthor variable, right where you define the author:
\\makeatletter \\title{\\textbf{\\underline{Assignment 2}}}\\let\\thetitle\\@title \\author{Devansh Kamra}\\let\\theauthor\\@author % Add this line \\makeatother
After making this change, recompile your document:
- The
fancyhdrheader will correctly display your title and author tidyversewill load without issues- The PDF will generate successfully
Optional: Fixing Overfull Hbox Warnings
If you want to get rid of those Overfull \\hbox messages, you can tweak your page margins slightly (e.g., increase them to 1.3in instead of 1.25in) in the geometry package setup. But this is totally optional—your PDF will work perfectly even with those warnings.
内容的提问来源于stack exchange,提问作者Devansh Kamra

